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,10 @@
|
||||
node_modules
|
||||
.next
|
||||
.git
|
||||
.env
|
||||
.env*.local
|
||||
data
|
||||
*.md
|
||||
Dockerfile
|
||||
docker-compose.yml
|
||||
.dockerignore
|
||||
@@ -0,0 +1,8 @@
|
||||
DATABASE_URL=postgresql://menu:${DB_PASSWORD}@db:5432/menu
|
||||
DB_PASSWORD=
|
||||
JWT_SECRET=
|
||||
ANTHROPIC_API_KEY=
|
||||
SUPERADMIN_USER=
|
||||
SUPERADMIN_PASSWORD=
|
||||
APP_BASE_URL=https://smartmenu.collinasystems.com.mx
|
||||
UPLOAD_DIR=/data/uploads
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/node_modules
|
||||
/.next
|
||||
/out
|
||||
/build
|
||||
.DS_Store
|
||||
*.pem
|
||||
.env
|
||||
.env*.local
|
||||
/data
|
||||
next-env.d.ts
|
||||
.vercel
|
||||
*.tsbuildinfo
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
# --- deps ---
|
||||
FROM node:20-alpine AS deps
|
||||
RUN apk add --no-cache libc6-compat openssl
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json* ./
|
||||
RUN npm ci
|
||||
|
||||
# --- builder ---
|
||||
FROM node:20-alpine AS builder
|
||||
RUN apk add --no-cache libc6-compat openssl
|
||||
WORKDIR /app
|
||||
COPY --from=deps /app/node_modules ./node_modules
|
||||
COPY . .
|
||||
RUN npx prisma generate
|
||||
RUN npm run build
|
||||
|
||||
# --- runner ---
|
||||
FROM node:20-alpine AS runner
|
||||
RUN apk add --no-cache libc6-compat openssl
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=3000
|
||||
|
||||
# Standalone output bundles only what's needed to run.
|
||||
COPY --from=builder /app/public ./public
|
||||
COPY --from=builder /app/.next/standalone ./
|
||||
COPY --from=builder /app/.next/static ./.next/static
|
||||
|
||||
# Prisma needs the schema + engine + CLI to run migrate deploy at startup.
|
||||
COPY --from=builder /app/prisma ./prisma
|
||||
COPY --from=builder /app/node_modules/.bin/prisma ./node_modules/.bin/prisma
|
||||
COPY --from=builder /app/node_modules/prisma ./node_modules/prisma
|
||||
COPY --from=builder /app/node_modules/@prisma ./node_modules/@prisma
|
||||
COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma
|
||||
|
||||
COPY docker-entrypoint.sh ./docker-entrypoint.sh
|
||||
RUN chmod +x docker-entrypoint.sh
|
||||
|
||||
EXPOSE 3000
|
||||
VOLUME ["/data"]
|
||||
CMD ["./docker-entrypoint.sh"]
|
||||
@@ -0,0 +1,116 @@
|
||||
# Menú inteligente — Collina Systems
|
||||
|
||||
Plataforma multi-tenant de menús digitales para restaurantes. Cada restaurante tiene su
|
||||
menú público (vía QR), un editor protegido mobile-first y un tablero de órdenes en tiempo
|
||||
real, con consultor IA y soporte bilingüe (ES/EN).
|
||||
|
||||
Estética: glassmorphism claro/transparente con animaciones high-end (flip 3D de macros,
|
||||
entradas escalonadas, micro-interacciones).
|
||||
|
||||
## Stack
|
||||
|
||||
- Next.js 14 (App Router) + TypeScript
|
||||
- PostgreSQL + Prisma
|
||||
- next-intl (ES/EN, switch por cookie sin cambiar URL)
|
||||
- Claude Haiku (`claude-haiku-4-5`) para traducción y consultor IA
|
||||
- SSE para órdenes en tiempo real
|
||||
- Almacenamiento en volumen local (`/data/uploads`)
|
||||
- Tailwind CSS
|
||||
- JWT + link secreto para auth del editor
|
||||
- Docker + docker-compose (listo para Coolify)
|
||||
|
||||
## Rutas
|
||||
|
||||
| Ruta | Descripción | Auth |
|
||||
| --- | --- | --- |
|
||||
| `/{slug}` | Menú público (QR) | — |
|
||||
| `/{slug}/editor?k={secret}` | Editor | link secreto + login |
|
||||
| `/{slug}/editor/login` | Login del editor | — |
|
||||
| `/admin` | Panel maestro Collina | superadmin (env) |
|
||||
|
||||
## Desarrollo local
|
||||
|
||||
```bash
|
||||
cp .env.example .env # completa los valores
|
||||
# DATABASE_URL apuntando a tu Postgres local, JWT_SECRET, ANTHROPIC_API_KEY,
|
||||
# SUPERADMIN_USER / SUPERADMIN_PASSWORD, APP_BASE_URL=http://localhost:3000
|
||||
|
||||
npm install
|
||||
npx prisma migrate deploy # o `npm run prisma:migrate` para desarrollo
|
||||
npm run db:seed # crea el restaurante demo (opcional)
|
||||
npm run dev
|
||||
```
|
||||
|
||||
El seed imprime el link de editor con su secreto y las credenciales `admin / demo1234`.
|
||||
|
||||
## Versionado (concepto clave)
|
||||
|
||||
- Las tablas `Section` y `Product` son el **borrador vivo** que el restaurante edita.
|
||||
- El menú público **nunca** lee el borrador: lee el `snapshot` JSON de la `MenuVersion`
|
||||
apuntada por `Restaurant.publishedVersionId`.
|
||||
- "Guardar y publicar" pide un nombre de versión, crea un `MenuVersion` con el snapshot
|
||||
completo del borrador y actualiza `publishedVersionId`.
|
||||
- Se conservan máximo **5 versiones** por restaurante; al publicar la 6ª se elimina la más
|
||||
vieja (nunca la publicada). Cada versión del historial se puede **restaurar** al borrador.
|
||||
|
||||
## Código de color de macros (estándar fijo)
|
||||
|
||||
Universal en todos los restaurantes — definido en `src/lib/macros.ts` y `tailwind.config.ts`.
|
||||
La paleta del restaurante (fondos, acentos, tabs) sí es configurable; la de macros no.
|
||||
|
||||
| Macro | Color |
|
||||
| --- | --- |
|
||||
| Proteína | `#C2410C` |
|
||||
| Carbohidratos | `#B45309` |
|
||||
| Azúcares | `#BE185D` |
|
||||
| Grasas | `#CA8A04` |
|
||||
| Fibra | `#15803D` |
|
||||
| Calorías | `#1D4ED8` |
|
||||
|
||||
## Despliegue con Coolify / Docker
|
||||
|
||||
`docker-compose.yml` define `app` (Next.js standalone) y `db` (Postgres 16) con volúmenes
|
||||
`menu_data` (uploads) y `menu_db`. El contenedor corre `prisma migrate deploy` al arrancar
|
||||
(ver `docker-entrypoint.sh`).
|
||||
|
||||
Variables de entorno (`.env`):
|
||||
|
||||
```env
|
||||
DATABASE_URL=postgresql://menu:${DB_PASSWORD}@db:5432/menu
|
||||
DB_PASSWORD=
|
||||
JWT_SECRET=
|
||||
ANTHROPIC_API_KEY=
|
||||
SUPERADMIN_USER=
|
||||
SUPERADMIN_PASSWORD=
|
||||
APP_BASE_URL=https://smartmenu.collinasystems.com.mx
|
||||
UPLOAD_DIR=/data/uploads
|
||||
```
|
||||
|
||||
```bash
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
En Coolify: apuntar al repo, montar el volumen persistente en `/data`, fijar las variables
|
||||
de entorno y el dominio `smartmenu.collinasystems.com.mx`.
|
||||
|
||||
## Endpoints
|
||||
|
||||
Públicos: `GET /api/{slug}/menu`, `POST /api/{slug}/order`, `POST /api/{slug}/call-waiter`,
|
||||
`POST /api/{slug}/ai-consult`, `GET /api/{slug}/orders/stream` (SSE).
|
||||
|
||||
Editor (JWT): `POST /api/{slug}/auth/login`, CRUD `sections`/`products`,
|
||||
`POST /api/{slug}/publish`, `GET /api/{slug}/versions`,
|
||||
`POST /api/{slug}/versions/{id}/restore`, `POST /api/{slug}/translate`,
|
||||
`POST /api/{slug}/upload`, `PATCH /api/{slug}/orders/{id}`, `PATCH /api/{slug}/palette`,
|
||||
`PATCH /api/{slug}/settings`, `GET /api/{slug}/qr`.
|
||||
|
||||
Superadmin: `POST /api/admin/login`, `GET|POST /api/admin/restaurants`,
|
||||
`PATCH /api/admin/restaurants/{id}`.
|
||||
|
||||
## Notas
|
||||
|
||||
- i18n de interfaz en `messages/{es,en}.json`; agregar un idioma = añadir un JSON nuevo.
|
||||
- Contenido dinámico (nombres/descripciones) se guarda como `{ es, en }`; el botón
|
||||
"Traducir con IA" llena el idioma faltante y marca `translationStatus.en` como `auto`
|
||||
hasta que el restaurante lo edita (`reviewed`).
|
||||
- Sentence case en toda la UI.
|
||||
@@ -0,0 +1,33 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
app:
|
||||
build: .
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- menu_data:/data
|
||||
env_file: [.env]
|
||||
ports:
|
||||
- '3000:3000'
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
|
||||
db:
|
||||
image: postgres:16-alpine
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- menu_db:/var/lib/postgresql/data
|
||||
environment:
|
||||
POSTGRES_DB: menu
|
||||
POSTGRES_USER: menu
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD}
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'pg_isready -U menu -d menu']
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
|
||||
volumes:
|
||||
menu_data:
|
||||
menu_db:
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
# Apply pending migrations against the database, then start the server.
|
||||
echo "Running prisma migrate deploy…"
|
||||
./node_modules/.bin/prisma migrate deploy
|
||||
|
||||
# Ensure the upload directory exists in the mounted volume.
|
||||
mkdir -p "${UPLOAD_DIR:-/data/uploads}"
|
||||
|
||||
echo "Starting Next.js…"
|
||||
exec node server.js
|
||||
@@ -0,0 +1,106 @@
|
||||
{
|
||||
"common": {
|
||||
"appName": "Smart menu",
|
||||
"save": "Save",
|
||||
"cancel": "Cancel",
|
||||
"delete": "Delete",
|
||||
"edit": "Edit",
|
||||
"add": "Add",
|
||||
"close": "Close",
|
||||
"loading": "Loading…",
|
||||
"back": "Back",
|
||||
"confirm": "Confirm",
|
||||
"restore": "Restore",
|
||||
"language": "Language"
|
||||
},
|
||||
"menu": {
|
||||
"askAi": "Ask the AI",
|
||||
"actions": "Actions",
|
||||
"placeOrder": "Place order",
|
||||
"callWaiter": "Call the waiter",
|
||||
"viewFull": "View full menu",
|
||||
"tableNumber": "Table number",
|
||||
"send": "Send",
|
||||
"addToOrder": "Add to order",
|
||||
"yourOrder": "Your order",
|
||||
"empty": "No dishes in this section yet.",
|
||||
"waiterCalled": "The waiter is on the way",
|
||||
"orderSent": "Your order was sent",
|
||||
"macroLegend": "Macro color code",
|
||||
"tapToFlip": "Tap to see macros"
|
||||
},
|
||||
"macros": {
|
||||
"protein": "Protein",
|
||||
"carbs": "Carbs",
|
||||
"sugar": "Sugars",
|
||||
"fat": "Fats",
|
||||
"fiber": "Fiber",
|
||||
"kcal": "Calories"
|
||||
},
|
||||
"ai": {
|
||||
"title": "Menu consultant",
|
||||
"placeholder": "What do you recommend if I'm diabetic?",
|
||||
"thinking": "Thinking…",
|
||||
"intro": "Tell me what you're after and I'll recommend dishes from the menu."
|
||||
},
|
||||
"editor": {
|
||||
"catalog": "Catalog",
|
||||
"palette": "Palette",
|
||||
"orders": "Orders",
|
||||
"qr": "QR",
|
||||
"publishedVersion": "Published version",
|
||||
"noVersion": "You haven't published a version yet",
|
||||
"addDish": "Add dish",
|
||||
"newSection": "New section",
|
||||
"viewMenu": "View menu",
|
||||
"saveAndPublish": "Save and publish",
|
||||
"versionNamePlaceholder": "Updated menu June 2026",
|
||||
"versionNameLabel": "Version name",
|
||||
"publishSuccess": "Done! Your menu «{name}» is now live",
|
||||
"history": "Version history",
|
||||
"historyHint": "You can see your last 5 versions",
|
||||
"translateAi": "Translate with AI",
|
||||
"autoTranslation": "Auto translation",
|
||||
"reviewedTranslation": "Reviewed",
|
||||
"complete": "Complete",
|
||||
"missingInfo": "Missing info",
|
||||
"active": "Active",
|
||||
"inactive": "Inactive",
|
||||
"name": "Name",
|
||||
"description": "Description",
|
||||
"price": "Price",
|
||||
"section": "Section",
|
||||
"allergens": "Allergens",
|
||||
"dietTags": "Diet tags",
|
||||
"media": "Photos and videos",
|
||||
"uploadMedia": "Upload photo or video",
|
||||
"ordersDisabled": "Order taking is disabled",
|
||||
"enableOrders": "Enable order taking",
|
||||
"completeOrder": "Complete order",
|
||||
"table": "Table",
|
||||
"downloadQr": "Download QR",
|
||||
"publicLink": "Public link",
|
||||
"copyLink": "Copy link",
|
||||
"copied": "Copied",
|
||||
"paletteHint": "This does not affect the macro color code"
|
||||
},
|
||||
"auth": {
|
||||
"login": "Log in",
|
||||
"username": "Username",
|
||||
"password": "Password",
|
||||
"invalid": "Wrong username or password",
|
||||
"invalidLink": "Invalid access link"
|
||||
},
|
||||
"admin": {
|
||||
"title": "Collina master panel",
|
||||
"newRestaurant": "New restaurant",
|
||||
"restaurants": "Restaurants",
|
||||
"name": "Name",
|
||||
"slug": "Slug",
|
||||
"create": "Create restaurant",
|
||||
"editorLink": "Editor link",
|
||||
"publicLink": "Public link",
|
||||
"credentials": "Initial credentials",
|
||||
"active": "Active"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
{
|
||||
"common": {
|
||||
"appName": "Menú inteligente",
|
||||
"save": "Guardar",
|
||||
"cancel": "Cancelar",
|
||||
"delete": "Eliminar",
|
||||
"edit": "Editar",
|
||||
"add": "Agregar",
|
||||
"close": "Cerrar",
|
||||
"loading": "Cargando…",
|
||||
"back": "Volver",
|
||||
"confirm": "Confirmar",
|
||||
"restore": "Restaurar",
|
||||
"language": "Idioma"
|
||||
},
|
||||
"menu": {
|
||||
"askAi": "Pregúntale a la IA",
|
||||
"actions": "Acciones",
|
||||
"placeOrder": "Realizar orden",
|
||||
"callWaiter": "Llamar al mesero",
|
||||
"viewFull": "Ver el menú completo",
|
||||
"tableNumber": "Número de mesa",
|
||||
"send": "Enviar",
|
||||
"addToOrder": "Agregar al pedido",
|
||||
"yourOrder": "Tu pedido",
|
||||
"empty": "Aún no hay platillos en esta sección.",
|
||||
"waiterCalled": "El mesero va en camino",
|
||||
"orderSent": "Tu orden fue enviada",
|
||||
"macroLegend": "Código de color de macros",
|
||||
"tapToFlip": "Toca para ver macros"
|
||||
},
|
||||
"macros": {
|
||||
"protein": "Proteína",
|
||||
"carbs": "Carbohidratos",
|
||||
"sugar": "Azúcares",
|
||||
"fat": "Grasas",
|
||||
"fiber": "Fibra",
|
||||
"kcal": "Calorías"
|
||||
},
|
||||
"ai": {
|
||||
"title": "Consultor del menú",
|
||||
"placeholder": "¿Qué me recomiendas si soy diabético?",
|
||||
"thinking": "Pensando…",
|
||||
"intro": "Cuéntame qué buscas y te recomiendo platillos del menú."
|
||||
},
|
||||
"editor": {
|
||||
"catalog": "Catálogo",
|
||||
"palette": "Paleta",
|
||||
"orders": "Órdenes",
|
||||
"qr": "QR",
|
||||
"publishedVersion": "Versión publicada",
|
||||
"noVersion": "Aún no has publicado una versión",
|
||||
"addDish": "Agregar platillo",
|
||||
"newSection": "Nueva sección",
|
||||
"viewMenu": "Ver menú",
|
||||
"saveAndPublish": "Guardar y publicar",
|
||||
"versionNamePlaceholder": "Carta actualizada junio 2026",
|
||||
"versionNameLabel": "Nombre de la versión",
|
||||
"publishSuccess": "¡Listo! Tu menú «{name}» ya está en vivo",
|
||||
"history": "Historial de versiones",
|
||||
"historyHint": "Puedes ver tus últimas 5 versiones",
|
||||
"translateAi": "Traducir con IA",
|
||||
"autoTranslation": "Traducción automática",
|
||||
"reviewedTranslation": "Revisada",
|
||||
"complete": "Completo",
|
||||
"missingInfo": "Falta info",
|
||||
"active": "Activo",
|
||||
"inactive": "Inactivo",
|
||||
"name": "Nombre",
|
||||
"description": "Descripción",
|
||||
"price": "Precio",
|
||||
"section": "Sección",
|
||||
"allergens": "Alérgenos",
|
||||
"dietTags": "Tags de dieta",
|
||||
"media": "Fotos y videos",
|
||||
"uploadMedia": "Subir foto o video",
|
||||
"ordersDisabled": "La toma de órdenes está desactivada",
|
||||
"enableOrders": "Habilitar toma de órdenes",
|
||||
"completeOrder": "Completar orden",
|
||||
"table": "Mesa",
|
||||
"downloadQr": "Descargar QR",
|
||||
"publicLink": "Link público",
|
||||
"copyLink": "Copiar link",
|
||||
"copied": "Copiado",
|
||||
"paletteHint": "Esto no afecta el código de color de macros"
|
||||
},
|
||||
"auth": {
|
||||
"login": "Iniciar sesión",
|
||||
"username": "Usuario",
|
||||
"password": "Contraseña",
|
||||
"invalid": "Usuario o contraseña incorrectos",
|
||||
"invalidLink": "Link de acceso inválido"
|
||||
},
|
||||
"admin": {
|
||||
"title": "Panel maestro Collina",
|
||||
"newRestaurant": "Nuevo restaurante",
|
||||
"restaurants": "Restaurantes",
|
||||
"name": "Nombre",
|
||||
"slug": "Slug",
|
||||
"create": "Crear restaurante",
|
||||
"editorLink": "Link de editor",
|
||||
"publicLink": "Link público",
|
||||
"credentials": "Credenciales iniciales",
|
||||
"active": "Activo"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import createNextIntlPlugin from 'next-intl/plugin';
|
||||
|
||||
const withNextIntl = createNextIntlPlugin('./src/i18n/request.ts');
|
||||
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
output: 'standalone',
|
||||
experimental: {
|
||||
// Body size limit for media uploads handled per-route.
|
||||
},
|
||||
};
|
||||
|
||||
export default withNextIntl(nextConfig);
|
||||
Generated
+2752
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"name": "smartmenu-collina",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "prisma generate && next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint",
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:migrate": "prisma migrate dev",
|
||||
"prisma:deploy": "prisma migrate deploy",
|
||||
"db:seed": "tsx prisma/seed.ts"
|
||||
},
|
||||
"prisma": {
|
||||
"seed": "tsx prisma/seed.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.65.0",
|
||||
"@prisma/client": "^5.22.0",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"clsx": "^2.1.1",
|
||||
"jose": "^5.9.6",
|
||||
"next": "14.2.21",
|
||||
"next-intl": "^3.26.3",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/node": "^20.17.10",
|
||||
"@types/qrcode": "^1.5.5",
|
||||
"@types/react": "^18.3.18",
|
||||
"@types/react-dom": "^18.3.5",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"postcss": "^8.4.49",
|
||||
"prisma": "^5.22.0",
|
||||
"tailwindcss": "^3.4.17",
|
||||
"tsx": "^4.19.2",
|
||||
"typescript": "^5.7.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
const config = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1,113 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "Restaurant" (
|
||||
"id" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"editorSecret" TEXT NOT NULL,
|
||||
"username" TEXT NOT NULL,
|
||||
"hashedPassword" TEXT NOT NULL,
|
||||
"palette" JSONB NOT NULL DEFAULT '{}',
|
||||
"ordersEnabled" BOOLEAN NOT NULL DEFAULT false,
|
||||
"defaultLocale" TEXT NOT NULL DEFAULT 'es',
|
||||
"active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"publishedVersionId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "Restaurant_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "MenuVersion" (
|
||||
"id" TEXT NOT NULL,
|
||||
"restaurantId" TEXT NOT NULL,
|
||||
"versionName" TEXT NOT NULL,
|
||||
"snapshot" JSONB NOT NULL,
|
||||
"publishedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"createdBy" TEXT,
|
||||
|
||||
CONSTRAINT "MenuVersion_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Section" (
|
||||
"id" TEXT NOT NULL,
|
||||
"restaurantId" TEXT NOT NULL,
|
||||
"name" JSONB NOT NULL,
|
||||
"order" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "Section_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Product" (
|
||||
"id" TEXT NOT NULL,
|
||||
"sectionId" TEXT NOT NULL,
|
||||
"restaurantId" TEXT NOT NULL,
|
||||
"name" JSONB NOT NULL,
|
||||
"description" JSONB NOT NULL DEFAULT '{}',
|
||||
"price" DECIMAL(10,2) NOT NULL DEFAULT 0,
|
||||
"order" INTEGER NOT NULL DEFAULT 0,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
"allergens" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||
"dietTags" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||
"macros" JSONB NOT NULL DEFAULT '{}',
|
||||
"media" JSONB NOT NULL DEFAULT '[]',
|
||||
"translationStatus" JSONB NOT NULL DEFAULT '{}',
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "Product_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Order" (
|
||||
"id" TEXT NOT NULL,
|
||||
"restaurantId" TEXT NOT NULL,
|
||||
"tableNumber" INTEGER NOT NULL,
|
||||
"items" JSONB NOT NULL,
|
||||
"status" TEXT NOT NULL DEFAULT 'active',
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"completedAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "Order_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Restaurant_slug_key" ON "Restaurant"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Restaurant_publishedVersionId_key" ON "Restaurant"("publishedVersionId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "MenuVersion_restaurantId_idx" ON "MenuVersion"("restaurantId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Section_restaurantId_idx" ON "Section"("restaurantId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Product_restaurantId_idx" ON "Product"("restaurantId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Product_sectionId_idx" ON "Product"("sectionId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Order_restaurantId_status_idx" ON "Order"("restaurantId", "status");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Restaurant" ADD CONSTRAINT "Restaurant_publishedVersionId_fkey" FOREIGN KEY ("publishedVersionId") REFERENCES "MenuVersion"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "MenuVersion" ADD CONSTRAINT "MenuVersion_restaurantId_fkey" FOREIGN KEY ("restaurantId") REFERENCES "Restaurant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Section" ADD CONSTRAINT "Section_restaurantId_fkey" FOREIGN KEY ("restaurantId") REFERENCES "Restaurant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Product" ADD CONSTRAINT "Product_sectionId_fkey" FOREIGN KEY ("sectionId") REFERENCES "Section"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Product" ADD CONSTRAINT "Product_restaurantId_fkey" FOREIGN KEY ("restaurantId") REFERENCES "Restaurant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Order" ADD CONSTRAINT "Order_restaurantId_fkey" FOREIGN KEY ("restaurantId") REFERENCES "Restaurant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (i.e. Git)
|
||||
provider = "postgresql"
|
||||
@@ -0,0 +1,96 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
model Restaurant {
|
||||
id String @id @default(cuid())
|
||||
slug String @unique
|
||||
name String
|
||||
editorSecret String
|
||||
username String
|
||||
hashedPassword String
|
||||
palette Json @default("{}")
|
||||
ordersEnabled Boolean @default(false)
|
||||
defaultLocale String @default("es")
|
||||
active Boolean @default(true)
|
||||
publishedVersionId String? @unique
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
publishedVersion MenuVersion? @relation("PublishedVersion", fields: [publishedVersionId], references: [id])
|
||||
versions MenuVersion[] @relation("RestaurantVersions")
|
||||
sections Section[]
|
||||
products Product[]
|
||||
orders Order[]
|
||||
}
|
||||
|
||||
// Versioning system: a published snapshot of the whole menu.
|
||||
model MenuVersion {
|
||||
id String @id @default(cuid())
|
||||
restaurantId String
|
||||
versionName String
|
||||
snapshot Json
|
||||
publishedAt DateTime @default(now())
|
||||
createdBy String?
|
||||
|
||||
restaurant Restaurant @relation("RestaurantVersions", fields: [restaurantId], references: [id], onDelete: Cascade)
|
||||
publishedFor Restaurant? @relation("PublishedVersion")
|
||||
|
||||
@@index([restaurantId])
|
||||
}
|
||||
|
||||
// Working DRAFT (not what the public sees).
|
||||
model Section {
|
||||
id String @id @default(cuid())
|
||||
restaurantId String
|
||||
name Json // { es, en }
|
||||
order Int @default(0)
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
restaurant Restaurant @relation(fields: [restaurantId], references: [id], onDelete: Cascade)
|
||||
products Product[]
|
||||
|
||||
@@index([restaurantId])
|
||||
}
|
||||
|
||||
// Working DRAFT product.
|
||||
model Product {
|
||||
id String @id @default(cuid())
|
||||
sectionId String
|
||||
restaurantId String
|
||||
name Json // { es, en }
|
||||
description Json @default("{}") // { es, en }
|
||||
price Decimal @default(0) @db.Decimal(10, 2)
|
||||
order Int @default(0)
|
||||
isActive Boolean @default(true)
|
||||
allergens String[] @default([])
|
||||
dietTags String[] @default([])
|
||||
macros Json @default("{}") // { protein, carbs, sugar, fat, fiber, kcal }
|
||||
media Json @default("[]") // [{ type, path, order }]
|
||||
translationStatus Json @default("{}") // { en: auto|reviewed }
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
section Section @relation(fields: [sectionId], references: [id], onDelete: Cascade)
|
||||
restaurant Restaurant @relation(fields: [restaurantId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([restaurantId])
|
||||
@@index([sectionId])
|
||||
}
|
||||
|
||||
model Order {
|
||||
id String @id @default(cuid())
|
||||
restaurantId String
|
||||
tableNumber Int
|
||||
items Json // [{ productId, name, qty }]
|
||||
status String @default("active") // active | completed
|
||||
createdAt DateTime @default(now())
|
||||
completedAt DateTime?
|
||||
|
||||
restaurant Restaurant @relation(fields: [restaurantId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([restaurantId, status])
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import crypto from 'crypto';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
// Seeds a demo restaurant so the app is browsable right after setup.
|
||||
async function main() {
|
||||
const slug = 'demo';
|
||||
const existing = await prisma.restaurant.findUnique({ where: { slug } });
|
||||
if (existing) {
|
||||
console.log('Demo restaurant already exists:', `/${slug}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const editorSecret = crypto.randomBytes(32).toString('base64url');
|
||||
const hashedPassword = await bcrypt.hash('demo1234', 10);
|
||||
|
||||
const restaurant = await prisma.restaurant.create({
|
||||
data: {
|
||||
slug,
|
||||
name: 'La Collina',
|
||||
editorSecret,
|
||||
username: 'admin',
|
||||
hashedPassword,
|
||||
defaultLocale: 'es',
|
||||
ordersEnabled: true,
|
||||
palette: {
|
||||
background: '#f4f1ec',
|
||||
surface: 'rgba(255,255,255,0.55)',
|
||||
accent: '#b45309',
|
||||
text: '#2a2520',
|
||||
tab: 'rgba(255,255,255,0.45)',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const starters = await prisma.section.create({
|
||||
data: { restaurantId: restaurant.id, name: { es: 'Entradas', en: 'Starters' }, order: 0 },
|
||||
});
|
||||
const mains = await prisma.section.create({
|
||||
data: { restaurantId: restaurant.id, name: { es: 'Platos fuertes', en: 'Main dishes' }, order: 1 },
|
||||
});
|
||||
|
||||
await prisma.product.create({
|
||||
data: {
|
||||
sectionId: starters.id,
|
||||
restaurantId: restaurant.id,
|
||||
name: { es: 'Ensalada de la casa', en: 'House salad' },
|
||||
description: {
|
||||
es: 'Verdes frescos, aderezo de la casa y nueces tostadas.',
|
||||
en: 'Fresh greens, house dressing and toasted walnuts.',
|
||||
},
|
||||
price: 120,
|
||||
order: 0,
|
||||
dietTags: ['vegetariano'],
|
||||
allergens: ['frutos secos'],
|
||||
macros: { protein: 6, carbs: 12, sugar: 4, fat: 9, fiber: 5, kcal: 180 },
|
||||
translationStatus: { en: 'reviewed' },
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.product.create({
|
||||
data: {
|
||||
sectionId: mains.id,
|
||||
restaurantId: restaurant.id,
|
||||
name: { es: 'Salmón a la parrilla', en: 'Grilled salmon' },
|
||||
description: {
|
||||
es: 'Salmón con vegetales de temporada y puré de papa.',
|
||||
en: 'Salmon with seasonal vegetables and mashed potato.',
|
||||
},
|
||||
price: 320,
|
||||
order: 0,
|
||||
allergens: ['pescado'],
|
||||
macros: { protein: 38, carbs: 22, sugar: 3, fat: 18, fiber: 4, kcal: 420 },
|
||||
translationStatus: { en: 'reviewed' },
|
||||
},
|
||||
});
|
||||
|
||||
console.log('Seeded demo restaurant.');
|
||||
console.log('Public:', `/${slug}`);
|
||||
console.log('Editor:', `/${slug}/editor?k=${editorSecret}`);
|
||||
console.log('Login: admin / demo1234');
|
||||
}
|
||||
|
||||
main()
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
})
|
||||
.finally(() => prisma.$disconnect());
|
||||
@@ -0,0 +1,27 @@
|
||||
import { notFound } from 'next/navigation';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import EditorLogin from '@/components/editor/EditorLogin';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default async function EditorLoginPage({
|
||||
params,
|
||||
searchParams,
|
||||
}: {
|
||||
params: { slug: string };
|
||||
searchParams: { k?: string };
|
||||
}) {
|
||||
const restaurant = await prisma.restaurant.findUnique({
|
||||
where: { slug: params.slug },
|
||||
select: { name: true, active: true },
|
||||
});
|
||||
if (!restaurant || !restaurant.active) notFound();
|
||||
|
||||
return (
|
||||
<EditorLogin
|
||||
slug={params.slug}
|
||||
name={restaurant.name}
|
||||
secret={searchParams.k ?? ''}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { redirect, notFound } from 'next/navigation';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { getEditorSession } from '@/lib/auth';
|
||||
import { paletteToCssVars } from '@/lib/palette';
|
||||
import type { EditorData } from '@/components/editor/types';
|
||||
import type { Palette } from '@/lib/types';
|
||||
import Editor from '@/components/editor/Editor';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default async function EditorPage({
|
||||
params,
|
||||
searchParams,
|
||||
}: {
|
||||
params: { slug: string };
|
||||
searchParams: { k?: string };
|
||||
}) {
|
||||
const restaurant = await prisma.restaurant.findUnique({
|
||||
where: { slug: params.slug },
|
||||
include: {
|
||||
publishedVersion: { select: { versionName: true } },
|
||||
sections: {
|
||||
orderBy: { order: 'asc' },
|
||||
include: { products: { orderBy: { order: 'asc' } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!restaurant || !restaurant.active) notFound();
|
||||
|
||||
const session = await getEditorSession(params.slug);
|
||||
if (!session) {
|
||||
const k = searchParams.k ? `?k=${encodeURIComponent(searchParams.k)}` : '';
|
||||
redirect(`/${params.slug}/editor/login${k}`);
|
||||
}
|
||||
|
||||
const data: EditorData = {
|
||||
slug: restaurant.slug,
|
||||
name: restaurant.name,
|
||||
ordersEnabled: restaurant.ordersEnabled,
|
||||
defaultLocale: restaurant.defaultLocale as 'es' | 'en',
|
||||
palette: (restaurant.palette as Palette) ?? {},
|
||||
publishedVersionName: restaurant.publishedVersion?.versionName ?? null,
|
||||
sections: restaurant.sections.map((s) => ({
|
||||
id: s.id,
|
||||
name: s.name as { es?: string; en?: string },
|
||||
order: s.order,
|
||||
products: s.products.map((p) => ({
|
||||
id: p.id,
|
||||
sectionId: p.sectionId,
|
||||
name: p.name as { es?: string; en?: string },
|
||||
description: p.description as { es?: string; en?: string },
|
||||
price: Number(p.price),
|
||||
order: p.order,
|
||||
isActive: p.isActive,
|
||||
allergens: p.allergens,
|
||||
dietTags: p.dietTags,
|
||||
macros: p.macros as Record<string, number>,
|
||||
media: p.media as { type: 'image' | 'video'; path: string; order: number }[],
|
||||
translationStatus: p.translationStatus as { en?: 'auto' | 'reviewed' },
|
||||
})),
|
||||
})),
|
||||
};
|
||||
|
||||
return (
|
||||
<main data-editor-root>
|
||||
<style>{`[data-editor-root]{${paletteToCssVars(restaurant.palette as Palette)}}`}</style>
|
||||
<Editor data={data} baseUrl={process.env.APP_BASE_URL || ''} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { notFound } from 'next/navigation';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { paletteToCssVars } from '@/lib/palette';
|
||||
import type { MenuSnapshot } from '@/lib/types';
|
||||
import PublicMenu from '@/components/public/PublicMenu';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
async function getPublishedMenu(slug: string): Promise<MenuSnapshot | null> {
|
||||
const restaurant = await prisma.restaurant.findUnique({
|
||||
where: { slug },
|
||||
include: { publishedVersion: true },
|
||||
});
|
||||
if (!restaurant || !restaurant.active) return null;
|
||||
if (!restaurant.publishedVersion) {
|
||||
// No version published yet — show an empty shell using live restaurant data.
|
||||
return {
|
||||
restaurant: {
|
||||
name: restaurant.name,
|
||||
slug: restaurant.slug,
|
||||
palette: (restaurant.palette as MenuSnapshot['restaurant']['palette']) ?? {},
|
||||
ordersEnabled: restaurant.ordersEnabled,
|
||||
defaultLocale: restaurant.defaultLocale as 'es' | 'en',
|
||||
},
|
||||
sections: [],
|
||||
};
|
||||
}
|
||||
return restaurant.publishedVersion.snapshot as unknown as MenuSnapshot;
|
||||
}
|
||||
|
||||
export default async function PublicMenuPage({ params }: { params: { slug: string } }) {
|
||||
const menu = await getPublishedMenu(params.slug);
|
||||
if (!menu) notFound();
|
||||
|
||||
return (
|
||||
<main data-menu-root>
|
||||
<style>{`:root{${paletteToCssVars(menu.restaurant.palette)}}`}</style>
|
||||
<PublicMenu menu={menu} slug={params.slug} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { isAdminAuthed } from '@/lib/auth';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import AdminLogin from '@/components/admin/AdminLogin';
|
||||
import AdminPanel from '@/components/admin/AdminPanel';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default async function AdminPage() {
|
||||
const authed = await isAdminAuthed();
|
||||
if (!authed) return <AdminLogin />;
|
||||
|
||||
const restaurants = await prisma.restaurant.findMany({
|
||||
orderBy: { createdAt: 'desc' },
|
||||
select: {
|
||||
id: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
editorSecret: true,
|
||||
username: true,
|
||||
active: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
const baseUrl = process.env.APP_BASE_URL || '';
|
||||
return <AdminPanel initialRestaurants={restaurants.map((r) => ({ ...r, createdAt: r.createdAt.toISOString() }))} baseUrl={baseUrl} />;
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
:root {
|
||||
/* Default restaurant palette (overridden per-restaurant at runtime). */
|
||||
--bg: #f4f1ec;
|
||||
--bg-2: #e9e3da;
|
||||
--surface: rgba(255, 255, 255, 0.55);
|
||||
--accent: #b45309;
|
||||
--text: #2a2520;
|
||||
--tab: rgba(255, 255, 255, 0.45);
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
color: var(--text);
|
||||
font-family: var(--font-inter), system-ui, sans-serif;
|
||||
background:
|
||||
radial-gradient(1200px 800px at 80% -10%, rgba(255, 255, 255, 0.6), transparent 60%),
|
||||
radial-gradient(1000px 700px at -10% 110%, rgba(255, 255, 255, 0.4), transparent 55%),
|
||||
linear-gradient(160deg, var(--bg), var(--bg-2));
|
||||
background-attachment: fixed;
|
||||
}
|
||||
|
||||
@layer components {
|
||||
.glass {
|
||||
background: var(--surface);
|
||||
backdrop-filter: blur(18px) saturate(140%);
|
||||
-webkit-backdrop-filter: blur(18px) saturate(140%);
|
||||
border: 1px solid rgba(255, 255, 255, 0.6);
|
||||
box-shadow:
|
||||
0 8px 32px rgba(31, 38, 135, 0.08),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.7);
|
||||
}
|
||||
|
||||
.glass-soft {
|
||||
background: rgba(255, 255, 255, 0.35);
|
||||
backdrop-filter: blur(12px);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.glass-pill {
|
||||
background: var(--tab);
|
||||
backdrop-filter: blur(14px);
|
||||
-webkit-backdrop-filter: blur(14px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.55);
|
||||
}
|
||||
|
||||
.display {
|
||||
font-family: var(--font-fraunces), Georgia, serif;
|
||||
}
|
||||
}
|
||||
|
||||
/* 3D flip card primitives */
|
||||
.flip-scene {
|
||||
perspective: 1400px;
|
||||
}
|
||||
.flip-card {
|
||||
position: relative;
|
||||
transform-style: preserve-3d;
|
||||
transition: transform 0.7s cubic-bezier(0.22, 1, 0.36, 1);
|
||||
}
|
||||
.flip-card.is-flipped {
|
||||
transform: rotateY(180deg);
|
||||
}
|
||||
.flip-face {
|
||||
backface-visibility: hidden;
|
||||
-webkit-backface-visibility: hidden;
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
}
|
||||
.flip-front {
|
||||
position: relative;
|
||||
}
|
||||
.flip-back {
|
||||
transform: rotateY(180deg);
|
||||
}
|
||||
|
||||
/* hide horizontal scrollbar on section tabs */
|
||||
.no-scrollbar::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
.no-scrollbar {
|
||||
-ms-overflow-style: none;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { Metadata, Viewport } from 'next';
|
||||
import { Fraunces, Inter } from 'next/font/google';
|
||||
import { NextIntlClientProvider } from 'next-intl';
|
||||
import { getLocale, getMessages } from 'next-intl/server';
|
||||
import './globals.css';
|
||||
|
||||
const fraunces = Fraunces({
|
||||
subsets: ['latin'],
|
||||
variable: '--font-fraunces',
|
||||
display: 'swap',
|
||||
});
|
||||
const inter = Inter({
|
||||
subsets: ['latin'],
|
||||
variable: '--font-inter',
|
||||
display: 'swap',
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Menú inteligente — Collina Systems',
|
||||
description: 'Menús digitales elegantes para restaurantes.',
|
||||
};
|
||||
|
||||
export const viewport: Viewport = {
|
||||
width: 'device-width',
|
||||
initialScale: 1,
|
||||
maximumScale: 1,
|
||||
themeColor: '#f4f1ec',
|
||||
};
|
||||
|
||||
export default async function RootLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const locale = await getLocale();
|
||||
const messages = await getMessages();
|
||||
|
||||
return (
|
||||
<html lang={locale} className={`${fraunces.variable} ${inter.variable}`}>
|
||||
<body>
|
||||
<NextIntlClientProvider locale={locale} messages={messages}>
|
||||
{children}
|
||||
</NextIntlClientProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import Link from 'next/link';
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<main className="flex min-h-screen flex-col items-center justify-center gap-6 p-6 text-center">
|
||||
<div className="glass max-w-md rounded-3xl p-8">
|
||||
<h1 className="display text-3xl font-semibold">Menú inteligente</h1>
|
||||
<p className="mt-2 text-sm text-[var(--text)]/65">
|
||||
Menús digitales elegantes para restaurantes · Collina Systems
|
||||
</p>
|
||||
<Link
|
||||
href="/admin"
|
||||
className="mt-6 inline-block rounded-full bg-[var(--accent)] px-6 py-3 text-sm font-medium text-white"
|
||||
>
|
||||
Panel maestro
|
||||
</Link>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
'use client';
|
||||
|
||||
import { useLocale } from 'next-intl';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useTransition } from 'react';
|
||||
import { LOCALE_COOKIE, locales, type Locale } from '@/i18n/config';
|
||||
|
||||
// Floating ES/EN toggle. Writes a cookie and refreshes server components so the
|
||||
// whole interface switches instantly.
|
||||
export default function LanguageSwitch({ className = '' }: { className?: string }) {
|
||||
const locale = useLocale() as Locale;
|
||||
const router = useRouter();
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
function setLocale(next: Locale) {
|
||||
if (next === locale) return;
|
||||
document.cookie = `${LOCALE_COOKIE}=${next}; path=/; max-age=31536000; samesite=lax`;
|
||||
startTransition(() => router.refresh());
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`glass-pill inline-flex rounded-full p-1 text-sm ${className}`}>
|
||||
{locales.map((l) => (
|
||||
<button
|
||||
key={l}
|
||||
onClick={() => setLocale(l)}
|
||||
disabled={pending}
|
||||
className={`rounded-full px-3 py-1 font-medium uppercase transition ${
|
||||
l === locale ? 'bg-white/70 text-[var(--text)] shadow' : 'text-[var(--text)]/60'
|
||||
}`}
|
||||
>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
export default function AdminLogin() {
|
||||
const router = useRouter();
|
||||
const [user, setUser] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError(false);
|
||||
const res = await fetch('/api/admin/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ user, password }),
|
||||
});
|
||||
setLoading(false);
|
||||
if (res.ok) router.refresh();
|
||||
else setError(true);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center p-4">
|
||||
<form onSubmit={submit} className="glass flex w-full max-w-sm flex-col gap-3 rounded-3xl p-6">
|
||||
<h1 className="display text-2xl font-semibold">Panel maestro Collina</h1>
|
||||
<input
|
||||
value={user}
|
||||
onChange={(e) => setUser(e.target.value)}
|
||||
placeholder="usuario"
|
||||
className="glass-soft rounded-2xl px-4 py-3 outline-none"
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="contraseña"
|
||||
className="glass-soft rounded-2xl px-4 py-3 outline-none"
|
||||
/>
|
||||
{error && <p className="text-sm text-red-600">Credenciales incorrectas</p>}
|
||||
<button
|
||||
disabled={loading}
|
||||
className="rounded-2xl bg-[var(--accent)] py-3 font-medium text-white disabled:opacity-50"
|
||||
>
|
||||
Iniciar sesión
|
||||
</button>
|
||||
</form>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
|
||||
type Restaurant = {
|
||||
id: string;
|
||||
slug: string;
|
||||
name: string;
|
||||
editorSecret: string;
|
||||
username: string;
|
||||
active: boolean;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
type Created = {
|
||||
slug: string;
|
||||
name: string;
|
||||
editorSecret: string;
|
||||
username: string;
|
||||
password: string;
|
||||
};
|
||||
|
||||
export default function AdminPanel({
|
||||
initialRestaurants,
|
||||
baseUrl,
|
||||
}: {
|
||||
initialRestaurants: Restaurant[];
|
||||
baseUrl: string;
|
||||
}) {
|
||||
const [restaurants, setRestaurants] = useState(initialRestaurants);
|
||||
const [name, setName] = useState('');
|
||||
const [slug, setSlug] = useState('');
|
||||
const [defaultLocale, setDefaultLocale] = useState('es');
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [justCreated, setJustCreated] = useState<Created | null>(null);
|
||||
|
||||
function publicLink(s: string) {
|
||||
return `${baseUrl}/${s}`;
|
||||
}
|
||||
function editorLink(r: { slug: string; editorSecret: string }) {
|
||||
return `${baseUrl}/${r.slug}/editor?k=${r.editorSecret}`;
|
||||
}
|
||||
|
||||
async function create(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!name.trim()) return;
|
||||
setCreating(true);
|
||||
const res = await fetch('/api/admin/restaurants', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name, slug, defaultLocale }),
|
||||
});
|
||||
setCreating(false);
|
||||
if (res.ok) {
|
||||
const data: Created = await res.json();
|
||||
setJustCreated(data);
|
||||
setName('');
|
||||
setSlug('');
|
||||
const list = await fetch('/api/admin/restaurants').then((r) => r.json());
|
||||
setRestaurants(list.restaurants);
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleActive(r: Restaurant) {
|
||||
await fetch(`/api/admin/restaurants/${r.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ active: !r.active }),
|
||||
});
|
||||
setRestaurants((prev) =>
|
||||
prev.map((x) => (x.id === r.id ? { ...x, active: !x.active } : x)),
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-3xl p-4 pb-16">
|
||||
<h1 className="display mb-6 text-3xl font-semibold">Panel maestro Collina</h1>
|
||||
|
||||
<section className="glass mb-6 rounded-3xl p-5">
|
||||
<h2 className="display mb-3 text-xl font-semibold">Nuevo restaurante</h2>
|
||||
<form onSubmit={create} className="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-end">
|
||||
<label className="flex flex-1 flex-col gap-1 text-sm">
|
||||
Nombre
|
||||
<input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
className="glass-soft rounded-2xl px-4 py-2.5 outline-none"
|
||||
/>
|
||||
</label>
|
||||
<label className="flex flex-1 flex-col gap-1 text-sm">
|
||||
Slug (opcional)
|
||||
<input
|
||||
value={slug}
|
||||
onChange={(e) => setSlug(e.target.value)}
|
||||
placeholder="se genera del nombre"
|
||||
className="glass-soft rounded-2xl px-4 py-2.5 outline-none"
|
||||
/>
|
||||
</label>
|
||||
<label className="flex flex-col gap-1 text-sm">
|
||||
Idioma
|
||||
<select
|
||||
value={defaultLocale}
|
||||
onChange={(e) => setDefaultLocale(e.target.value)}
|
||||
className="glass-soft rounded-2xl px-4 py-2.5 outline-none"
|
||||
>
|
||||
<option value="es">ES</option>
|
||||
<option value="en">EN</option>
|
||||
</select>
|
||||
</label>
|
||||
<button
|
||||
disabled={creating}
|
||||
className="rounded-2xl bg-[var(--accent)] px-5 py-2.5 font-medium text-white disabled:opacity-50"
|
||||
>
|
||||
Crear restaurante
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{justCreated && (
|
||||
<div className="mt-4 rounded-2xl border border-amber-300 bg-amber-50/70 p-4 text-sm">
|
||||
<p className="mb-2 font-semibold">
|
||||
Restaurante «{justCreated.name}» creado. Guarda estas credenciales (se muestran una vez):
|
||||
</p>
|
||||
<ul className="space-y-1">
|
||||
<li>
|
||||
<strong>Usuario:</strong> {justCreated.username}
|
||||
</li>
|
||||
<li>
|
||||
<strong>Contraseña:</strong> <code>{justCreated.password}</code>
|
||||
</li>
|
||||
<li className="break-all">
|
||||
<strong>Link de editor:</strong> {editorLink(justCreated)}
|
||||
</li>
|
||||
<li className="break-all">
|
||||
<strong>Link público:</strong> {publicLink(justCreated.slug)}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="glass rounded-3xl p-5">
|
||||
<h2 className="display mb-3 text-xl font-semibold">Restaurantes</h2>
|
||||
<div className="flex flex-col gap-3">
|
||||
{restaurants.length === 0 && <p className="text-sm text-[var(--text)]/60">Aún no hay restaurantes.</p>}
|
||||
{restaurants.map((r) => (
|
||||
<div key={r.id} className="glass-soft rounded-2xl p-4">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div>
|
||||
<div className="font-semibold">{r.name}</div>
|
||||
<div className="text-xs text-[var(--text)]/60">/{r.slug}</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => toggleActive(r)}
|
||||
className={`rounded-full px-3 py-1 text-xs font-medium ${
|
||||
r.active ? 'bg-green-100 text-green-800' : 'bg-gray-200 text-gray-600'
|
||||
}`}
|
||||
>
|
||||
{r.active ? 'activo' : 'inactivo'}
|
||||
</button>
|
||||
</div>
|
||||
<div className="mt-2 space-y-1 text-xs">
|
||||
<a href={publicLink(r.slug)} target="_blank" className="block break-all text-[var(--accent)]">
|
||||
público: {publicLink(r.slug)}
|
||||
</a>
|
||||
<a href={editorLink(r)} target="_blank" className="block break-all text-[var(--accent)]">
|
||||
editor: {editorLink(r)}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useLocale, useTranslations } from 'next-intl';
|
||||
import type { Locale } from '@/i18n/config';
|
||||
import type { EditorProduct, EditorSection } from './types';
|
||||
import { pickText } from '@/lib/text';
|
||||
import { api } from './api';
|
||||
import ProductEditor from './ProductEditor';
|
||||
import SectionTitleEditor from './SectionTitleEditor';
|
||||
import VersionHistory from './VersionHistory';
|
||||
|
||||
export default function CatalogTab({
|
||||
slug,
|
||||
sections,
|
||||
setSections,
|
||||
ordersEnabled,
|
||||
onPublish,
|
||||
onRestored,
|
||||
}: {
|
||||
slug: string;
|
||||
sections: EditorSection[];
|
||||
setSections: React.Dispatch<React.SetStateAction<EditorSection[]>>;
|
||||
ordersEnabled: boolean;
|
||||
onPublish: () => void;
|
||||
onRestored: (name: string | null) => void;
|
||||
}) {
|
||||
const t = useTranslations('editor');
|
||||
const locale = useLocale() as Locale;
|
||||
const [editing, setEditing] = useState<{ product: EditorProduct } | null>(null);
|
||||
const [dragSection, setDragSection] = useState<string | null>(null);
|
||||
const [dragProduct, setDragProduct] = useState<{ sectionId: string; id: string } | null>(null);
|
||||
|
||||
async function addSection() {
|
||||
const name = { es: 'Nueva sección', en: 'New section' };
|
||||
const created = await api<{ id: string }>(slug, '/sections', { method: 'POST', json: { name } });
|
||||
setSections((prev) => [...prev, { id: created.id, name, order: prev.length, products: [] }]);
|
||||
}
|
||||
|
||||
async function deleteSection(id: string) {
|
||||
await api(slug, `/sections/${id}`, { method: 'DELETE' });
|
||||
setSections((prev) => prev.filter((s) => s.id !== id));
|
||||
}
|
||||
|
||||
async function addProduct(sectionId: string) {
|
||||
const created = await api<EditorProduct>(slug, '/products', {
|
||||
method: 'POST',
|
||||
json: { sectionId, name: { es: '', en: '' } },
|
||||
});
|
||||
const product: EditorProduct = {
|
||||
...created,
|
||||
price: Number(created.price),
|
||||
macros: created.macros ?? {},
|
||||
media: created.media ?? [],
|
||||
allergens: created.allergens ?? [],
|
||||
dietTags: created.dietTags ?? [],
|
||||
translationStatus: created.translationStatus ?? {},
|
||||
};
|
||||
setSections((prev) =>
|
||||
prev.map((s) => (s.id === sectionId ? { ...s, products: [...s.products, product] } : s)),
|
||||
);
|
||||
setEditing({ product });
|
||||
}
|
||||
|
||||
function applyProduct(updated: EditorProduct) {
|
||||
setSections((prev) =>
|
||||
prev.map((s) =>
|
||||
s.id === updated.sectionId
|
||||
? { ...s, products: s.products.map((p) => (p.id === updated.id ? updated : p)) }
|
||||
: s,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function deleteProduct(p: EditorProduct) {
|
||||
await api(slug, `/products/${p.id}`, { method: 'DELETE' });
|
||||
setSections((prev) =>
|
||||
prev.map((s) =>
|
||||
s.id === p.sectionId ? { ...s, products: s.products.filter((x) => x.id !== p.id) } : s,
|
||||
),
|
||||
);
|
||||
setEditing(null);
|
||||
}
|
||||
|
||||
async function toggleActive(p: EditorProduct) {
|
||||
const next = !p.isActive;
|
||||
await api(slug, `/products/${p.id}`, { method: 'PATCH', json: { isActive: next } });
|
||||
applyProduct({ ...p, isActive: next });
|
||||
}
|
||||
|
||||
// Section reordering (native drag).
|
||||
function reorderSections(targetId: string) {
|
||||
if (!dragSection || dragSection === targetId) return;
|
||||
setSections((prev) => {
|
||||
const from = prev.findIndex((s) => s.id === dragSection);
|
||||
const to = prev.findIndex((s) => s.id === targetId);
|
||||
const next = [...prev];
|
||||
const [moved] = next.splice(from, 1);
|
||||
next.splice(to, 0, moved);
|
||||
api(slug, '/sections', { method: 'PATCH', json: { ids: next.map((s) => s.id) } });
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
function reorderProducts(sectionId: string, targetId: string) {
|
||||
if (!dragProduct || dragProduct.sectionId !== sectionId || dragProduct.id === targetId) return;
|
||||
setSections((prev) =>
|
||||
prev.map((s) => {
|
||||
if (s.id !== sectionId) return s;
|
||||
const from = s.products.findIndex((p) => p.id === dragProduct.id);
|
||||
const to = s.products.findIndex((p) => p.id === targetId);
|
||||
const products = [...s.products];
|
||||
const [moved] = products.splice(from, 1);
|
||||
products.splice(to, 0, moved);
|
||||
api(slug, '/products', { method: 'PATCH', json: { sectionId, ids: products.map((p) => p.id) } });
|
||||
return { ...s, products };
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function status(p: EditorProduct): 'complete' | 'missing' {
|
||||
const hasMacros = Object.values(p.macros).some((v) => v != null);
|
||||
const hasMedia = p.media.length > 0;
|
||||
const hasName = !!(p.name.es || p.name.en);
|
||||
return hasMacros && hasMedia && hasName ? 'complete' : 'missing';
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<a
|
||||
href={`/${slug}`}
|
||||
target="_blank"
|
||||
className="glass-pill rounded-full px-4 py-2 text-sm font-medium"
|
||||
>
|
||||
👁 {t('viewMenu')}
|
||||
</a>
|
||||
<button
|
||||
onClick={onPublish}
|
||||
className="ml-auto rounded-full bg-[var(--accent)] px-5 py-2 text-sm font-semibold text-white shadow"
|
||||
>
|
||||
{t('saveAndPublish')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{sections.map((s) => (
|
||||
<section
|
||||
key={s.id}
|
||||
className="glass rounded-3xl p-4"
|
||||
draggable
|
||||
onDragStart={() => setDragSection(s.id)}
|
||||
onDragEnd={() => setDragSection(null)}
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDrop={() => reorderSections(s.id)}
|
||||
>
|
||||
<div className="mb-3 flex items-center gap-2">
|
||||
<span className="cursor-grab text-[var(--text)]/30" title="Arrastrar">
|
||||
⋮⋮
|
||||
</span>
|
||||
<SectionTitleEditor
|
||||
slug={slug}
|
||||
section={s}
|
||||
onRename={(name) =>
|
||||
setSections((prev) => prev.map((x) => (x.id === s.id ? { ...x, name } : x)))
|
||||
}
|
||||
/>
|
||||
<button
|
||||
onClick={() => deleteSection(s.id)}
|
||||
className="ml-auto text-sm text-red-500/70"
|
||||
aria-label={t('delete')}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
{s.products.map((p) => (
|
||||
<div
|
||||
key={p.id}
|
||||
className="glass-soft flex items-center gap-3 rounded-2xl p-2"
|
||||
draggable
|
||||
onDragStart={(e) => {
|
||||
e.stopPropagation();
|
||||
setDragProduct({ sectionId: s.id, id: p.id });
|
||||
}}
|
||||
onDragEnd={() => setDragProduct(null)}
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDrop={(e) => {
|
||||
e.stopPropagation();
|
||||
reorderProducts(s.id, p.id);
|
||||
}}
|
||||
>
|
||||
<span className="cursor-grab text-[var(--text)]/30">⋮⋮</span>
|
||||
<div className="h-12 w-12 shrink-0 overflow-hidden rounded-xl bg-white/40">
|
||||
{p.media[0] ? (
|
||||
p.media[0].type === 'video' ? (
|
||||
// eslint-disable-next-line jsx-a11y/media-has-caption
|
||||
<video src={p.media[0].path} className="h-full w-full object-cover" muted />
|
||||
) : (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={p.media[0].path} alt="" className="h-full w-full object-cover" />
|
||||
)
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center">🍽️</div>
|
||||
)}
|
||||
</div>
|
||||
<button onClick={() => setEditing({ product: p })} className="min-w-0 flex-1 text-left">
|
||||
<div className="truncate text-sm font-medium">
|
||||
{pickText(p.name, locale) || '—'}
|
||||
</div>
|
||||
<div className="text-xs text-[var(--text)]/55">${p.price.toFixed(2)}</div>
|
||||
</button>
|
||||
<span
|
||||
className={`h-2.5 w-2.5 rounded-full ${
|
||||
status(p) === 'complete' ? 'bg-green-500' : 'bg-amber-500'
|
||||
}`}
|
||||
title={status(p) === 'complete' ? t('complete') : t('missingInfo')}
|
||||
/>
|
||||
<button
|
||||
onClick={() => toggleActive(p)}
|
||||
className={`rounded-full px-2 py-1 text-[10px] font-medium ${
|
||||
p.isActive ? 'bg-green-100 text-green-700' : 'bg-gray-200 text-gray-500'
|
||||
}`}
|
||||
>
|
||||
{p.isActive ? t('active') : t('inactive')}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => addProduct(s.id)}
|
||||
className="mt-3 w-full rounded-2xl border border-dashed border-[var(--accent)]/40 py-2 text-sm font-medium text-[var(--accent)]"
|
||||
>
|
||||
+ {t('addDish')}
|
||||
</button>
|
||||
</section>
|
||||
))}
|
||||
|
||||
<button
|
||||
onClick={addSection}
|
||||
className="glass-pill rounded-2xl py-3 text-sm font-medium"
|
||||
>
|
||||
+ {t('newSection')}
|
||||
</button>
|
||||
|
||||
<VersionHistory slug={slug} onRestored={onRestored} />
|
||||
|
||||
{editing && (
|
||||
<ProductEditor
|
||||
slug={slug}
|
||||
product={editing.product}
|
||||
sections={sections}
|
||||
onClose={() => setEditing(null)}
|
||||
onSave={applyProduct}
|
||||
onDelete={deleteProduct}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import type { EditorData, EditorSection } from './types';
|
||||
import LanguageSwitch from '@/components/LanguageSwitch';
|
||||
import CatalogTab from './CatalogTab';
|
||||
import PaletteTab from './PaletteTab';
|
||||
import OrdersTab from './OrdersTab';
|
||||
import QrTab from './QrTab';
|
||||
import PublishModal from './PublishModal';
|
||||
|
||||
type Tab = 'catalog' | 'palette' | 'orders' | 'qr';
|
||||
|
||||
export default function Editor({ data, baseUrl }: { data: EditorData; baseUrl: string }) {
|
||||
const t = useTranslations('editor');
|
||||
const [tab, setTab] = useState<Tab>('catalog');
|
||||
const [sections, setSections] = useState<EditorSection[]>(data.sections);
|
||||
const [ordersEnabled, setOrdersEnabled] = useState(data.ordersEnabled);
|
||||
const [publishOpen, setPublishOpen] = useState(false);
|
||||
const [publishedName, setPublishedName] = useState(data.publishedVersionName);
|
||||
|
||||
const tabs: { id: Tab; label: string; icon: string }[] = [
|
||||
{ id: 'catalog', label: t('catalog'), icon: '📋' },
|
||||
{ id: 'palette', label: t('palette'), icon: '🎨' },
|
||||
{ id: 'orders', label: t('orders'), icon: '🔔' },
|
||||
{ id: 'qr', label: t('qr'), icon: '🔳' },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="mx-auto min-h-screen max-w-2xl px-4 pb-28 pt-4">
|
||||
<header className="mb-3 flex items-center justify-between gap-2">
|
||||
<div>
|
||||
<h1 className="display text-xl font-semibold leading-tight">{data.name}</h1>
|
||||
<p className="text-xs text-[var(--text)]/55">
|
||||
{publishedName ? `${t('publishedVersion')}: ${publishedName}` : t('noVersion')}
|
||||
</p>
|
||||
</div>
|
||||
<LanguageSwitch />
|
||||
</header>
|
||||
|
||||
{tab === 'catalog' && (
|
||||
<CatalogTab
|
||||
slug={data.slug}
|
||||
sections={sections}
|
||||
setSections={setSections}
|
||||
ordersEnabled={ordersEnabled}
|
||||
onPublish={() => setPublishOpen(true)}
|
||||
onRestored={(name) => setPublishedName(name)}
|
||||
/>
|
||||
)}
|
||||
{tab === 'palette' && <PaletteTab slug={data.slug} initialPalette={data.palette} />}
|
||||
{tab === 'orders' && (
|
||||
<OrdersTab
|
||||
slug={data.slug}
|
||||
ordersEnabled={ordersEnabled}
|
||||
setOrdersEnabled={setOrdersEnabled}
|
||||
/>
|
||||
)}
|
||||
{tab === 'qr' && <QrTab slug={data.slug} baseUrl={baseUrl} />}
|
||||
|
||||
{/* Bottom tab bar */}
|
||||
<nav className="glass fixed bottom-0 left-1/2 z-30 flex w-full max-w-2xl -translate-x-1/2 items-stretch justify-around rounded-t-3xl px-2 py-2">
|
||||
{tabs.map((x) => (
|
||||
<button
|
||||
key={x.id}
|
||||
onClick={() => setTab(x.id)}
|
||||
className={`flex flex-1 flex-col items-center gap-0.5 rounded-2xl py-2 text-[11px] font-medium transition ${
|
||||
tab === x.id ? 'bg-white/60 text-[var(--accent)]' : 'text-[var(--text)]/60'
|
||||
}`}
|
||||
>
|
||||
<span className="text-lg">{x.icon}</span>
|
||||
{x.label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
{publishOpen && (
|
||||
<PublishModal
|
||||
slug={data.slug}
|
||||
onClose={() => setPublishOpen(false)}
|
||||
onPublished={(name) => {
|
||||
setPublishedName(name);
|
||||
setPublishOpen(false);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useTranslations } from 'next-intl';
|
||||
|
||||
export default function EditorLogin({
|
||||
slug,
|
||||
name,
|
||||
secret,
|
||||
}: {
|
||||
slug: string;
|
||||
name: string;
|
||||
secret: string;
|
||||
}) {
|
||||
const t = useTranslations('auth');
|
||||
const router = useRouter();
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const res = await fetch(`/api/${slug}/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password, secret }),
|
||||
});
|
||||
setLoading(false);
|
||||
if (res.ok) {
|
||||
router.push(`/${slug}/editor`);
|
||||
router.refresh();
|
||||
} else {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
setError(data.error === 'invalid_link' ? t('invalidLink') : t('invalid'));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center p-4">
|
||||
<form onSubmit={submit} className="glass flex w-full max-w-sm flex-col gap-3 rounded-3xl p-6">
|
||||
<h1 className="display text-2xl font-semibold">{name}</h1>
|
||||
<p className="text-sm text-[var(--text)]/60">{t('login')}</p>
|
||||
{!secret && <p className="text-sm text-amber-700">{t('invalidLink')}</p>}
|
||||
<input
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder={t('username')}
|
||||
autoCapitalize="none"
|
||||
className="glass-soft rounded-2xl px-4 py-3 outline-none"
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder={t('password')}
|
||||
className="glass-soft rounded-2xl px-4 py-3 outline-none"
|
||||
/>
|
||||
{error && <p className="text-sm text-red-600">{error}</p>}
|
||||
<button
|
||||
disabled={loading || !secret}
|
||||
className="rounded-2xl bg-[var(--accent)] py-3 font-medium text-white disabled:opacity-50"
|
||||
>
|
||||
{t('login')}
|
||||
</button>
|
||||
</form>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import type { OrderItem } from '@/lib/types';
|
||||
import { api } from './api';
|
||||
|
||||
type Order = {
|
||||
id: string;
|
||||
tableNumber: number;
|
||||
items: OrderItem[];
|
||||
createdAt: string;
|
||||
status: string;
|
||||
};
|
||||
|
||||
type WaiterCall = { tableNumber: number; at: string };
|
||||
|
||||
export default function OrdersTab({
|
||||
slug,
|
||||
ordersEnabled,
|
||||
setOrdersEnabled,
|
||||
}: {
|
||||
slug: string;
|
||||
ordersEnabled: boolean;
|
||||
setOrdersEnabled: (v: boolean) => void;
|
||||
}) {
|
||||
const t = useTranslations('editor');
|
||||
const [orders, setOrders] = useState<Order[]>([]);
|
||||
const [waiterCalls, setWaiterCalls] = useState<WaiterCall[]>([]);
|
||||
const [now, setNow] = useState(() => 0);
|
||||
const esRef = useRef<EventSource | null>(null);
|
||||
|
||||
// Tick every second to drive timers (avoids Date in render init).
|
||||
useEffect(() => {
|
||||
setNow(Date.now());
|
||||
const id = setInterval(() => setNow(Date.now()), 1000);
|
||||
return () => clearInterval(id);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ordersEnabled) return;
|
||||
const es = new EventSource(`/api/${slug}/orders/stream`);
|
||||
esRef.current = es;
|
||||
|
||||
es.addEventListener('snapshot', (e) => {
|
||||
setOrders(JSON.parse((e as MessageEvent).data));
|
||||
});
|
||||
es.addEventListener('order', (e) => {
|
||||
const order: Order = JSON.parse((e as MessageEvent).data);
|
||||
setOrders((prev) => [...prev, order]);
|
||||
});
|
||||
es.addEventListener('order-update', (e) => {
|
||||
const { id, status } = JSON.parse((e as MessageEvent).data);
|
||||
setOrders((prev) =>
|
||||
status === 'active' ? prev : prev.filter((o) => o.id !== id),
|
||||
);
|
||||
});
|
||||
es.addEventListener('waiter', (e) => {
|
||||
const call: WaiterCall = JSON.parse((e as MessageEvent).data);
|
||||
setWaiterCalls((prev) => [call, ...prev].slice(0, 8));
|
||||
});
|
||||
|
||||
return () => es.close();
|
||||
}, [slug, ordersEnabled]);
|
||||
|
||||
async function toggleOrders() {
|
||||
const next = !ordersEnabled;
|
||||
setOrdersEnabled(next);
|
||||
await api(slug, '/settings', { method: 'PATCH', json: { ordersEnabled: next } });
|
||||
}
|
||||
|
||||
async function complete(o: Order) {
|
||||
setOrders((prev) => prev.filter((x) => x.id !== o.id));
|
||||
await api(slug, `/orders/${o.id}`, { method: 'PATCH', json: { status: 'completed' } });
|
||||
}
|
||||
|
||||
function elapsed(createdAt: string): { label: string; color: string } {
|
||||
const secs = Math.max(0, Math.floor((now - new Date(createdAt).getTime()) / 1000));
|
||||
const m = Math.floor(secs / 60);
|
||||
const s = secs % 60;
|
||||
const label = `${m}:${s.toString().padStart(2, '0')}`;
|
||||
// green → amber → red as time grows.
|
||||
const color = secs < 300 ? '#15803d' : secs < 600 ? '#b45309' : '#dc2626';
|
||||
return { label, color };
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="glass flex items-center justify-between rounded-3xl p-4">
|
||||
<span className="text-sm font-medium">{t('enableOrders')}</span>
|
||||
<button
|
||||
onClick={toggleOrders}
|
||||
className={`relative h-7 w-12 rounded-full transition ${
|
||||
ordersEnabled ? 'bg-green-500' : 'bg-gray-300'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`absolute top-1 h-5 w-5 rounded-full bg-white transition-all ${
|
||||
ordersEnabled ? 'left-6' : 'left-1'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{!ordersEnabled && (
|
||||
<p className="text-center text-sm text-[var(--text)]/55">{t('ordersDisabled')}</p>
|
||||
)}
|
||||
|
||||
{ordersEnabled && waiterCalls.length > 0 && (
|
||||
<div className="flex flex-col gap-2">
|
||||
{waiterCalls.map((c, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="animate-spawn flex items-center gap-2 rounded-2xl bg-amber-100/80 px-4 py-2 text-sm text-amber-800"
|
||||
>
|
||||
🔔{' '}
|
||||
<strong>
|
||||
{t('table')} {c.tableNumber}
|
||||
</strong>
|
||||
<button
|
||||
onClick={() => setWaiterCalls((prev) => prev.filter((_, idx) => idx !== i))}
|
||||
className="ml-auto"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{ordersEnabled && (
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
{orders.map((o) => {
|
||||
const e = elapsed(o.createdAt);
|
||||
return (
|
||||
<div key={o.id} className="animate-spawn glass relative rounded-3xl p-4">
|
||||
<button
|
||||
onClick={() => complete(o)}
|
||||
className="absolute right-3 top-3 text-lg text-[var(--text)]/40"
|
||||
aria-label={t('completeOrder')}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
<div className="flex items-center justify-between pr-6">
|
||||
<span className="display text-lg font-semibold">
|
||||
{t('table')} {o.tableNumber}
|
||||
</span>
|
||||
<span
|
||||
className="rounded-full px-2 py-0.5 font-mono text-sm font-semibold text-white"
|
||||
style={{ background: e.color }}
|
||||
>
|
||||
{e.label}
|
||||
</span>
|
||||
</div>
|
||||
<ul className="mt-2 space-y-1 text-sm">
|
||||
{o.items.map((it, idx) => (
|
||||
<li key={idx} className="flex justify-between">
|
||||
<span>{it.name}</span>
|
||||
<span className="text-[var(--text)]/60">×{it.qty}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<button
|
||||
onClick={() => complete(o)}
|
||||
className="mt-3 w-full rounded-2xl bg-[var(--accent)] py-2 text-sm font-medium text-white"
|
||||
>
|
||||
{t('completeOrder')}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import type { Palette } from '@/lib/types';
|
||||
import { PALETTE_PRESETS } from '@/lib/palette';
|
||||
import { api } from './api';
|
||||
|
||||
const FIELDS: { key: keyof Palette; label: string }[] = [
|
||||
{ key: 'background', label: 'Fondo' },
|
||||
{ key: 'accent', label: 'Acento' },
|
||||
{ key: 'text', label: 'Texto' },
|
||||
];
|
||||
|
||||
export default function PaletteTab({
|
||||
slug,
|
||||
initialPalette,
|
||||
}: {
|
||||
slug: string;
|
||||
initialPalette: Palette;
|
||||
}) {
|
||||
const t = useTranslations('editor');
|
||||
const tc = useTranslations('common');
|
||||
const [palette, setPalette] = useState<Palette>({
|
||||
...PALETTE_PRESETS[0].palette,
|
||||
...initialPalette,
|
||||
});
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saved, setSaved] = useState(false);
|
||||
|
||||
function update(next: Palette) {
|
||||
setPalette(next);
|
||||
setSaved(false);
|
||||
}
|
||||
|
||||
async function save() {
|
||||
setSaving(true);
|
||||
try {
|
||||
await api(slug, '/palette', { method: 'PATCH', json: { palette } });
|
||||
setSaved(true);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Live preview */}
|
||||
<div
|
||||
className="rounded-3xl p-5"
|
||||
style={{ background: palette.background }}
|
||||
>
|
||||
<div
|
||||
className="rounded-2xl border border-white/60 p-4"
|
||||
style={{ background: palette.surface, backdropFilter: 'blur(12px)' }}
|
||||
>
|
||||
<h3 className="display text-lg font-semibold" style={{ color: palette.text }}>
|
||||
Vista previa
|
||||
</h3>
|
||||
<button
|
||||
className="mt-2 rounded-full px-4 py-2 text-sm text-white"
|
||||
style={{ background: palette.accent }}
|
||||
>
|
||||
Acento
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Presets */}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{PALETTE_PRESETS.map((p) => (
|
||||
<button
|
||||
key={p.id}
|
||||
onClick={() => update({ ...p.palette })}
|
||||
className="glass-soft flex items-center gap-2 rounded-full px-3 py-2 text-sm"
|
||||
>
|
||||
<span
|
||||
className="h-4 w-4 rounded-full border border-white/60"
|
||||
style={{ background: p.palette.accent }}
|
||||
/>
|
||||
{p.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Custom colors */}
|
||||
<div className="glass rounded-3xl p-4">
|
||||
<div className="flex flex-col gap-3">
|
||||
{FIELDS.map((f) => (
|
||||
<label key={f.key} className="flex items-center justify-between text-sm">
|
||||
{f.label}
|
||||
<input
|
||||
type="color"
|
||||
value={palette[f.key] ?? '#ffffff'}
|
||||
onChange={(e) => update({ ...palette, [f.key]: e.target.value })}
|
||||
className="h-9 w-16 rounded-lg border-0 bg-transparent"
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-[var(--text)]/55">⚠️ {t('paletteHint')}</p>
|
||||
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import type { EditorProduct, EditorSection } from './types';
|
||||
import { MACRO_KEYS } from '@/lib/macros';
|
||||
import { api } from './api';
|
||||
|
||||
const ALLERGENS = ['gluten', 'lácteos', 'frutos secos', 'mariscos', 'huevo', 'soya', 'pescado'];
|
||||
const DIET_TAGS = ['vegetariano', 'vegano', 'sin gluten', 'sin lácteos', 'keto', 'picante'];
|
||||
|
||||
export default function ProductEditor({
|
||||
slug,
|
||||
product,
|
||||
sections,
|
||||
onClose,
|
||||
onSave,
|
||||
onDelete,
|
||||
}: {
|
||||
slug: string;
|
||||
product: EditorProduct;
|
||||
sections: EditorSection[];
|
||||
onClose: () => void;
|
||||
onSave: (p: EditorProduct) => void;
|
||||
onDelete: (p: EditorProduct) => void;
|
||||
}) {
|
||||
const t = useTranslations('editor');
|
||||
const tm = useTranslations('macros');
|
||||
const [draft, setDraft] = useState<EditorProduct>(product);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [translating, setTranslating] = useState<string | null>(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
|
||||
function set<K extends keyof EditorProduct>(key: K, value: EditorProduct[K]) {
|
||||
setDraft((d) => ({ ...d, [key]: value }));
|
||||
}
|
||||
|
||||
async function save() {
|
||||
setSaving(true);
|
||||
try {
|
||||
await api(slug, `/products/${draft.id}`, {
|
||||
method: 'PATCH',
|
||||
json: {
|
||||
name: draft.name,
|
||||
description: draft.description,
|
||||
price: draft.price,
|
||||
sectionId: draft.sectionId,
|
||||
allergens: draft.allergens,
|
||||
dietTags: draft.dietTags,
|
||||
macros: draft.macros,
|
||||
media: draft.media,
|
||||
translationStatus: draft.translationStatus,
|
||||
},
|
||||
});
|
||||
onSave(draft);
|
||||
onClose();
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function translate(field: 'name' | 'description') {
|
||||
const from = draft[field].es ? 'es' : 'en';
|
||||
const text = draft[field][from];
|
||||
if (!text) return;
|
||||
setTranslating(field);
|
||||
try {
|
||||
const res = await api<{ translation: string; to: 'es' | 'en' }>(slug, '/translate', {
|
||||
method: 'POST',
|
||||
json: { text, from },
|
||||
});
|
||||
setDraft((d) => ({
|
||||
...d,
|
||||
[field]: { ...d[field], [res.to]: res.translation },
|
||||
translationStatus: { ...d.translationStatus, en: 'auto' as const },
|
||||
}));
|
||||
} finally {
|
||||
setTranslating(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function upload(files: FileList | null) {
|
||||
if (!files?.length) return;
|
||||
setUploading(true);
|
||||
try {
|
||||
const added: EditorProduct['media'] = [];
|
||||
for (const file of Array.from(files)) {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
const res = await api<{ path: string; type: 'image' | 'video' }>(slug, '/upload', {
|
||||
method: 'POST',
|
||||
body: form,
|
||||
});
|
||||
added.push({ type: res.type, path: res.path, order: draft.media.length + added.length });
|
||||
}
|
||||
setDraft((d) => ({ ...d, media: [...d.media, ...added] }));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function moveMedia(index: number, dir: -1 | 1) {
|
||||
setDraft((d) => {
|
||||
const media = [...d.media];
|
||||
const to = index + dir;
|
||||
if (to < 0 || to >= media.length) return d;
|
||||
[media[index], media[to]] = [media[to], media[index]];
|
||||
return { ...d, media: media.map((m, i) => ({ ...m, order: i })) };
|
||||
});
|
||||
}
|
||||
|
||||
function removeMedia(index: number) {
|
||||
setDraft((d) => ({
|
||||
...d,
|
||||
media: d.media.filter((_, i) => i !== index).map((m, i) => ({ ...m, order: i })),
|
||||
}));
|
||||
}
|
||||
|
||||
function toggleIn(list: string[], value: string): string[] {
|
||||
return list.includes(value) ? list.filter((x) => x !== value) : [...list, value];
|
||||
}
|
||||
|
||||
const enStatus = draft.translationStatus.en;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-end justify-center bg-black/40 p-2 backdrop-blur-sm sm:items-center">
|
||||
<div className="glass flex max-h-[92vh] w-full max-w-lg flex-col gap-4 overflow-y-auto rounded-3xl p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="display text-lg font-semibold">{t('edit')}</h3>
|
||||
<button onClick={onClose} className="glass-pill rounded-full px-3 py-1">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Name ES/EN */}
|
||||
<Field label={t('name')}>
|
||||
<div className="flex flex-col gap-2">
|
||||
<LocaleInput
|
||||
prefix="ES"
|
||||
value={draft.name.es ?? ''}
|
||||
onChange={(v) => set('name', { ...draft.name, es: v })}
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<LocaleInput
|
||||
prefix="EN"
|
||||
value={draft.name.en ?? ''}
|
||||
onChange={(v) =>
|
||||
setDraft((d) => ({
|
||||
...d,
|
||||
name: { ...d.name, en: v },
|
||||
translationStatus: { ...d.translationStatus, en: 'reviewed' },
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<TranslateRow
|
||||
loading={translating === 'name'}
|
||||
status={enStatus}
|
||||
onClick={() => translate('name')}
|
||||
/>
|
||||
</div>
|
||||
</Field>
|
||||
|
||||
{/* Description ES/EN */}
|
||||
<Field label={t('description')}>
|
||||
<div className="flex flex-col gap-2">
|
||||
<textarea
|
||||
value={draft.description.es ?? ''}
|
||||
onChange={(e) => set('description', { ...draft.description, es: e.target.value })}
|
||||
placeholder="ES"
|
||||
rows={2}
|
||||
className="glass-soft rounded-2xl px-3 py-2 text-sm outline-none"
|
||||
/>
|
||||
<textarea
|
||||
value={draft.description.en ?? ''}
|
||||
onChange={(e) =>
|
||||
setDraft((d) => ({
|
||||
...d,
|
||||
description: { ...d.description, en: e.target.value },
|
||||
translationStatus: { ...d.translationStatus, en: 'reviewed' },
|
||||
}))
|
||||
}
|
||||
placeholder="EN"
|
||||
rows={2}
|
||||
className="glass-soft rounded-2xl px-3 py-2 text-sm outline-none"
|
||||
/>
|
||||
<TranslateRow
|
||||
loading={translating === 'description'}
|
||||
status={enStatus}
|
||||
onClick={() => translate('description')}
|
||||
/>
|
||||
</div>
|
||||
</Field>
|
||||
|
||||
{/* Price + Section */}
|
||||
<div className="flex gap-3">
|
||||
<Field label={t('price')} className="flex-1">
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min={0}
|
||||
value={draft.price}
|
||||
onChange={(e) => set('price', Number(e.target.value))}
|
||||
className="glass-soft w-full rounded-2xl px-3 py-2 outline-none"
|
||||
/>
|
||||
</Field>
|
||||
<Field label={t('section')} className="flex-1">
|
||||
<select
|
||||
value={draft.sectionId}
|
||||
onChange={(e) => set('sectionId', e.target.value)}
|
||||
className="glass-soft w-full rounded-2xl px-3 py-2 outline-none"
|
||||
>
|
||||
{sections.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name.es || s.name.en}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
{/* Media */}
|
||||
<Field label={t('media')}>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{draft.media.map((m, i) => (
|
||||
<div key={i} className="relative h-20 w-20 overflow-hidden rounded-xl bg-white/40">
|
||||
{m.type === 'video' ? (
|
||||
// eslint-disable-next-line jsx-a11y/media-has-caption
|
||||
<video src={m.path} className="h-full w-full object-cover" muted />
|
||||
) : (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={m.path} alt="" className="h-full w-full object-cover" />
|
||||
)}
|
||||
<button
|
||||
onClick={() => removeMedia(i)}
|
||||
className="absolute right-0 top-0 bg-black/50 px-1 text-xs text-white"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
<div className="absolute bottom-0 flex w-full justify-between bg-black/40 text-xs text-white">
|
||||
<button onClick={() => moveMedia(i, -1)} className="px-1">
|
||||
‹
|
||||
</button>
|
||||
<button onClick={() => moveMedia(i, 1)} className="px-1">
|
||||
›
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<label className="flex h-20 w-20 cursor-pointer items-center justify-center rounded-xl border border-dashed border-[var(--accent)]/40 text-2xl text-[var(--accent)]">
|
||||
{uploading ? '…' : '+'}
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*,video/*"
|
||||
multiple
|
||||
hidden
|
||||
onChange={(e) => upload(e.target.files)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</Field>
|
||||
|
||||
{/* Macros */}
|
||||
<Field label="Macros">
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{MACRO_KEYS.map((key) => (
|
||||
<label key={key} className="flex flex-col gap-1 text-xs">
|
||||
{tm(key)}
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
value={draft.macros[key] ?? ''}
|
||||
onChange={(e) =>
|
||||
set('macros', {
|
||||
...draft.macros,
|
||||
[key]: e.target.value === '' ? undefined : Number(e.target.value),
|
||||
} as Record<string, number>)
|
||||
}
|
||||
className="glass-soft rounded-xl px-2 py-1.5 outline-none"
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</Field>
|
||||
|
||||
{/* Allergens */}
|
||||
<Field label={t('allergens')}>
|
||||
<Chips
|
||||
options={ALLERGENS}
|
||||
selected={draft.allergens}
|
||||
onToggle={(v) => set('allergens', toggleIn(draft.allergens, v))}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
{/* Diet tags */}
|
||||
<Field label={t('dietTags')}>
|
||||
<Chips
|
||||
options={DIET_TAGS}
|
||||
selected={draft.dietTags}
|
||||
onToggle={(v) => set('dietTags', toggleIn(draft.dietTags, v))}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<div className="flex gap-2 pt-1">
|
||||
<button
|
||||
onClick={() => onDelete(draft)}
|
||||
className="rounded-2xl bg-red-100 px-4 py-3 text-sm font-medium text-red-700"
|
||||
>
|
||||
{t('delete')}
|
||||
</button>
|
||||
<button
|
||||
onClick={save}
|
||||
disabled={saving}
|
||||
className="flex-1 rounded-2xl bg-[var(--accent)] py-3 font-medium text-white disabled:opacity-50"
|
||||
>
|
||||
{t('save')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Field({
|
||||
label,
|
||||
children,
|
||||
className = '',
|
||||
}: {
|
||||
label: string;
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className={`flex flex-col gap-1.5 ${className}`}>
|
||||
<span className="text-xs font-medium text-[var(--text)]/60">{label}</span>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LocaleInput({
|
||||
prefix,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
prefix: string;
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="glass-soft flex items-center gap-2 rounded-2xl px-3">
|
||||
<span className="text-[10px] font-bold text-[var(--text)]/40">{prefix}</span>
|
||||
<input
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className="flex-1 bg-transparent py-2 text-sm outline-none"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TranslateRow({
|
||||
loading,
|
||||
status,
|
||||
onClick,
|
||||
}: {
|
||||
loading: boolean;
|
||||
status?: 'auto' | 'reviewed';
|
||||
onClick: () => void;
|
||||
}) {
|
||||
const t = useTranslations('editor');
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={onClick}
|
||||
disabled={loading}
|
||||
className="glass-pill rounded-full px-3 py-1 text-xs font-medium disabled:opacity-50"
|
||||
>
|
||||
{loading ? '…' : `✨ ${t('translateAi')}`}
|
||||
</button>
|
||||
{status && (
|
||||
<span
|
||||
className={`rounded-full px-2 py-0.5 text-[10px] ${
|
||||
status === 'auto' ? 'bg-amber-100 text-amber-700' : 'bg-green-100 text-green-700'
|
||||
}`}
|
||||
>
|
||||
{status === 'auto' ? t('autoTranslation') : t('reviewedTranslation')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Chips({
|
||||
options,
|
||||
selected,
|
||||
onToggle,
|
||||
}: {
|
||||
options: string[];
|
||||
selected: string[];
|
||||
onToggle: (v: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{options.map((o) => (
|
||||
<button
|
||||
key={o}
|
||||
onClick={() => onToggle(o)}
|
||||
className={`rounded-full px-3 py-1 text-xs transition ${
|
||||
selected.includes(o)
|
||||
? 'bg-[var(--accent)] text-white'
|
||||
: 'glass-soft text-[var(--text)]/70'
|
||||
}`}
|
||||
>
|
||||
{o}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { api } from './api';
|
||||
|
||||
export default function PublishModal({
|
||||
slug,
|
||||
onClose,
|
||||
onPublished,
|
||||
}: {
|
||||
slug: string;
|
||||
onClose: () => void;
|
||||
onPublished: (name: string) => void;
|
||||
}) {
|
||||
const t = useTranslations('editor');
|
||||
const tc = useTranslations('common');
|
||||
const [name, setName] = useState('');
|
||||
const [publishing, setPublishing] = useState(false);
|
||||
const [success, setSuccess] = useState<string | null>(null);
|
||||
|
||||
async function publish() {
|
||||
if (!name.trim() || publishing) return;
|
||||
setPublishing(true);
|
||||
try {
|
||||
const res = await api<{ versionName: string }>(slug, '/publish', {
|
||||
method: 'POST',
|
||||
json: { versionName: name.trim() },
|
||||
});
|
||||
setSuccess(res.versionName);
|
||||
onPublished(res.versionName);
|
||||
} finally {
|
||||
setPublishing(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-end justify-center bg-black/40 p-3 backdrop-blur-sm sm:items-center">
|
||||
<div className="glass flex w-full max-w-md flex-col gap-3 rounded-3xl p-5">
|
||||
{success ? (
|
||||
<>
|
||||
<div className="text-center text-4xl">✅</div>
|
||||
<p className="text-center text-sm">{t('publishSuccess', { name: success })}</p>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="rounded-2xl bg-[var(--accent)] py-3 font-medium text-white"
|
||||
>
|
||||
{tc('close')}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<h3 className="display text-lg font-semibold">{t('saveAndPublish')}</h3>
|
||||
<label className="flex flex-col gap-1 text-sm">
|
||||
{t('versionNameLabel')}
|
||||
<input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder={t('versionNamePlaceholder')}
|
||||
autoFocus
|
||||
className="glass-soft rounded-2xl px-4 py-3 outline-none"
|
||||
/>
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<button onClick={onClose} className="glass-pill flex-1 rounded-2xl py-3 text-sm">
|
||||
{tc('cancel')}
|
||||
</button>
|
||||
<button
|
||||
onClick={publish}
|
||||
disabled={!name.trim() || publishing}
|
||||
className="flex-1 rounded-2xl bg-[var(--accent)] py-3 font-medium text-white disabled:opacity-50"
|
||||
>
|
||||
{t('saveAndPublish')}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
|
||||
export default function QrTab({ slug, baseUrl }: { slug: string; baseUrl: string }) {
|
||||
const t = useTranslations('editor');
|
||||
const [copied, setCopied] = useState(false);
|
||||
const link = `${baseUrl || (typeof window !== 'undefined' ? window.location.origin : '')}/${slug}`;
|
||||
|
||||
async function copy() {
|
||||
await navigator.clipboard.writeText(link);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 1800);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-5">
|
||||
<div className="glass rounded-3xl p-6">
|
||||
{/* Live PNG from the QR endpoint */}
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={`/api/${slug}/qr?format=png`}
|
||||
alt="QR"
|
||||
className="h-60 w-60 rounded-2xl bg-white"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="glass flex w-full max-w-sm items-center gap-2 rounded-2xl px-4 py-3">
|
||||
<span className="min-w-0 flex-1 truncate text-sm">{link}</span>
|
||||
<button onClick={copy} className="glass-pill rounded-full px-3 py-1 text-xs font-medium">
|
||||
{copied ? t('copied') : t('copyLink')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<a
|
||||
href={`/api/${slug}/qr?format=png`}
|
||||
download
|
||||
className="rounded-2xl bg-[var(--accent)] px-5 py-3 text-sm font-medium text-white"
|
||||
>
|
||||
{t('downloadQr')} PNG
|
||||
</a>
|
||||
<a
|
||||
href={`/api/${slug}/qr?format=svg`}
|
||||
download
|
||||
className="glass-pill rounded-2xl px-5 py-3 text-sm font-medium"
|
||||
>
|
||||
SVG
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useLocale } from 'next-intl';
|
||||
import type { Locale } from '@/i18n/config';
|
||||
import type { EditorSection } from './types';
|
||||
import { pickText } from '@/lib/text';
|
||||
import { api } from './api';
|
||||
|
||||
// Inline-editable section title for the active locale.
|
||||
export default function SectionTitleEditor({
|
||||
slug,
|
||||
section,
|
||||
onRename,
|
||||
}: {
|
||||
slug: string;
|
||||
section: EditorSection;
|
||||
onRename: (name: { es?: string; en?: string }) => void;
|
||||
}) {
|
||||
const locale = useLocale() as Locale;
|
||||
const [value, setValue] = useState(pickText(section.name, locale));
|
||||
|
||||
async function commit() {
|
||||
const name = { ...section.name, [locale]: value };
|
||||
onRename(name);
|
||||
await api(slug, `/sections/${section.id}`, { method: 'PATCH', json: { name } });
|
||||
}
|
||||
|
||||
return (
|
||||
<input
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
onBlur={commit}
|
||||
className="display flex-1 bg-transparent text-lg font-semibold outline-none"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useLocale, useTranslations } from 'next-intl';
|
||||
import { api } from './api';
|
||||
|
||||
type Version = {
|
||||
id: string;
|
||||
versionName: string;
|
||||
publishedAt: string;
|
||||
createdBy: string | null;
|
||||
};
|
||||
|
||||
export default function VersionHistory({
|
||||
slug,
|
||||
onRestored,
|
||||
}: {
|
||||
slug: string;
|
||||
onRestored: (name: string | null) => void;
|
||||
}) {
|
||||
const t = useTranslations('editor');
|
||||
const tc = useTranslations('common');
|
||||
const locale = useLocale();
|
||||
const [versions, setVersions] = useState<Version[]>([]);
|
||||
const [publishedId, setPublishedId] = useState<string | null>(null);
|
||||
const [restoring, setRestoring] = useState<string | null>(null);
|
||||
|
||||
async function load() {
|
||||
const res = await api<{ versions: Version[]; publishedVersionId: string | null }>(
|
||||
slug,
|
||||
'/versions',
|
||||
);
|
||||
setVersions(res.versions);
|
||||
setPublishedId(res.publishedVersionId);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
async function restore(v: Version) {
|
||||
setRestoring(v.id);
|
||||
try {
|
||||
await api(slug, `/versions/${v.id}/restore`, { method: 'POST' });
|
||||
onRestored(v.versionName);
|
||||
// Reload to pull the freshly restored draft into the editor.
|
||||
window.location.reload();
|
||||
} finally {
|
||||
setRestoring(null);
|
||||
}
|
||||
}
|
||||
|
||||
if (versions.length === 0) return null;
|
||||
|
||||
return (
|
||||
<section className="glass rounded-3xl p-4">
|
||||
<h2 className="display mb-1 text-lg font-semibold">{t('history')}</h2>
|
||||
<p className="mb-3 text-xs text-[var(--text)]/55">{t('historyHint')}</p>
|
||||
<div className="flex flex-col gap-2">
|
||||
{versions.map((v) => (
|
||||
<div key={v.id} className="glass-soft flex items-center gap-2 rounded-2xl px-3 py-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm font-medium">
|
||||
{v.versionName}
|
||||
{v.id === publishedId && (
|
||||
<span className="ml-2 rounded-full bg-green-100 px-2 py-0.5 text-[10px] text-green-700">
|
||||
{t('publishedVersion')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-[11px] text-[var(--text)]/55">
|
||||
{new Date(v.publishedAt).toLocaleDateString(locale, {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => restore(v)}
|
||||
disabled={restoring === v.id}
|
||||
className="glass-pill rounded-full px-3 py-1 text-xs font-medium disabled:opacity-50"
|
||||
>
|
||||
{tc('restore')}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Thin client helpers for editor API calls.
|
||||
export async function api<T = unknown>(
|
||||
slug: string,
|
||||
path: string,
|
||||
options?: RequestInit & { json?: unknown },
|
||||
): Promise<T> {
|
||||
const { json, ...rest } = options ?? {};
|
||||
const res = await fetch(`/api/${slug}${path}`, {
|
||||
...rest,
|
||||
headers: {
|
||||
...(json ? { 'Content-Type': 'application/json' } : {}),
|
||||
...(rest.headers ?? {}),
|
||||
},
|
||||
body: json ? JSON.stringify(json) : rest.body,
|
||||
});
|
||||
if (!res.ok) throw new Error(`${res.status}`);
|
||||
const text = await res.text();
|
||||
return text ? (JSON.parse(text) as T) : (undefined as T);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { Locale } from '@/i18n/config';
|
||||
import type { Palette } from '@/lib/types';
|
||||
|
||||
export type EditorProduct = {
|
||||
id: string;
|
||||
sectionId: string;
|
||||
name: { es?: string; en?: string };
|
||||
description: { es?: string; en?: string };
|
||||
price: number;
|
||||
order: number;
|
||||
isActive: boolean;
|
||||
allergens: string[];
|
||||
dietTags: string[];
|
||||
macros: Record<string, number>;
|
||||
media: { type: 'image' | 'video'; path: string; order: number }[];
|
||||
translationStatus: { en?: 'auto' | 'reviewed' };
|
||||
};
|
||||
|
||||
export type EditorSection = {
|
||||
id: string;
|
||||
name: { es?: string; en?: string };
|
||||
order: number;
|
||||
products: EditorProduct[];
|
||||
};
|
||||
|
||||
export type EditorData = {
|
||||
slug: string;
|
||||
name: string;
|
||||
ordersEnabled: boolean;
|
||||
defaultLocale: Locale;
|
||||
palette: Palette;
|
||||
publishedVersionName: string | null;
|
||||
sections: EditorSection[];
|
||||
};
|
||||
@@ -0,0 +1,86 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useLocale, useTranslations } from 'next-intl';
|
||||
|
||||
type Recommendation = { dish: string; reason: string };
|
||||
|
||||
export default function AiConsultant({ slug, onClose }: { slug: string; onClose: () => void }) {
|
||||
const t = useTranslations('ai');
|
||||
const locale = useLocale();
|
||||
const [question, setQuestion] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [answer, setAnswer] = useState<{ intro?: string; recommendations: Recommendation[] } | null>(
|
||||
null,
|
||||
);
|
||||
const [error, setError] = useState(false);
|
||||
|
||||
async function ask() {
|
||||
if (!question.trim() || loading) return;
|
||||
setLoading(true);
|
||||
setError(false);
|
||||
setAnswer(null);
|
||||
try {
|
||||
const res = await fetch(`/api/${slug}/ai-consult`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ question, locale }),
|
||||
});
|
||||
if (!res.ok) throw new Error('failed');
|
||||
setAnswer(await res.json());
|
||||
} catch {
|
||||
setError(true);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-end justify-center bg-black/40 p-3 backdrop-blur-sm sm:items-center">
|
||||
<div className="glass flex max-h-[85vh] w-full max-w-md flex-col gap-3 rounded-3xl p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="display text-lg font-semibold">{t('title')}</h3>
|
||||
<button onClick={onClose} className="glass-pill rounded-full px-3 py-1">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="min-h-[6rem] flex-1 overflow-y-auto">
|
||||
{!answer && !loading && (
|
||||
<p className="text-sm text-[var(--text)]/60">{t('intro')}</p>
|
||||
)}
|
||||
{loading && <p className="animate-pulse text-sm text-[var(--text)]/60">{t('thinking')}</p>}
|
||||
{error && <p className="text-sm text-red-600">⚠️</p>}
|
||||
{answer && (
|
||||
<div className="flex flex-col gap-2">
|
||||
{answer.intro && <p className="text-sm text-[var(--text)]/80">{answer.intro}</p>}
|
||||
{answer.recommendations.map((r, i) => (
|
||||
<div key={i} className="glass-soft rounded-2xl p-3">
|
||||
<div className="font-semibold text-[var(--accent)]">{r.dish}</div>
|
||||
<p className="text-sm text-[var(--text)]/80">{r.reason}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
value={question}
|
||||
onChange={(e) => setQuestion(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && ask()}
|
||||
placeholder={t('placeholder')}
|
||||
className="glass-soft flex-1 rounded-full px-4 py-2 text-sm outline-none"
|
||||
/>
|
||||
<button
|
||||
onClick={ask}
|
||||
disabled={loading}
|
||||
className="rounded-full bg-[var(--accent)] px-4 py-2 text-sm font-medium text-white disabled:opacity-50"
|
||||
>
|
||||
→
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
'use client';
|
||||
|
||||
import { useState } 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';
|
||||
import MacrosBack from './MacrosBack';
|
||||
|
||||
export default function DishCard({
|
||||
product,
|
||||
index,
|
||||
onOpenGallery,
|
||||
onAdd,
|
||||
ordersEnabled,
|
||||
}: {
|
||||
product: SnapshotProduct;
|
||||
index: number;
|
||||
onOpenGallery: (p: SnapshotProduct) => void;
|
||||
onAdd?: (p: SnapshotProduct) => void;
|
||||
ordersEnabled: boolean;
|
||||
}) {
|
||||
const locale = useLocale() as Locale;
|
||||
const t = useTranslations('menu');
|
||||
const [flipped, setFlipped] = useState(false);
|
||||
|
||||
const name = pickText(product.name, locale);
|
||||
const description = pickText(product.description, locale);
|
||||
const sortedMedia = [...product.media].sort((a, b) => a.order - b.order);
|
||||
const cover = sortedMedia[0];
|
||||
const hasVideo = sortedMedia.some((m) => m.type === 'video');
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flip-scene animate-fade-up"
|
||||
style={{ animationDelay: `${Math.min(index * 70, 500)}ms` }}
|
||||
>
|
||||
<div className={`flip-card min-h-[20rem] ${flipped ? 'is-flipped' : ''}`}>
|
||||
{/* FRONT */}
|
||||
<div className="flip-face flip-front glass overflow-hidden rounded-3xl">
|
||||
<button
|
||||
className="relative block h-40 w-full"
|
||||
onClick={() => onOpenGallery(product)}
|
||||
aria-label={name}
|
||||
>
|
||||
<MediaThumb media={cover} alt={name} className="h-40 w-full" />
|
||||
{hasVideo && (
|
||||
<span className="absolute right-3 top-3 h-3 w-3 animate-pulse-dot rounded-full bg-red-500 shadow" />
|
||||
)}
|
||||
</button>
|
||||
<div className="flex flex-col gap-2 p-4">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<h3 className="display text-lg font-semibold leading-tight">{name}</h3>
|
||||
<span className="shrink-0 text-base font-bold text-[var(--accent)]">
|
||||
${product.price.toFixed(2)}
|
||||
</span>
|
||||
</div>
|
||||
{description && (
|
||||
<p className="line-clamp-2 text-sm text-[var(--text)]/70">{description}</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{product.dietTags.map((tag) => (
|
||||
<span key={tag} className="glass-soft rounded-full px-2 py-0.5 text-[11px]">
|
||||
{tag}
|
||||
</span>
|
||||
))}
|
||||
{product.allergens.map((a) => (
|
||||
<span
|
||||
key={a}
|
||||
className="rounded-full bg-amber-100/60 px-2 py-0.5 text-[11px] text-amber-800"
|
||||
>
|
||||
{a}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-1 flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => setFlipped(true)}
|
||||
className="glass-pill flex-1 rounded-full py-2 text-sm font-medium"
|
||||
>
|
||||
{t('tapToFlip')}
|
||||
</button>
|
||||
{ordersEnabled && onAdd && (
|
||||
<button
|
||||
onClick={() => onAdd(product)}
|
||||
className="rounded-full bg-[var(--accent)] px-4 py-2 text-sm font-medium text-white"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* BACK */}
|
||||
<div className="flip-face flip-back glass flex flex-col gap-3 rounded-3xl p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="display text-base font-semibold">{name}</h3>
|
||||
<button
|
||||
onClick={() => setFlipped(false)}
|
||||
className="glass-pill rounded-full px-3 py-1 text-sm"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
<MacrosBack macros={product.macros} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
'use client';
|
||||
|
||||
import { useLocale } from 'next-intl';
|
||||
import type { Locale } from '@/i18n/config';
|
||||
import type { SnapshotProduct } from '@/lib/types';
|
||||
import { pickText } from '@/lib/text';
|
||||
import MacrosBack from './MacrosBack';
|
||||
|
||||
// Full-screen gallery: all media of a product + expanded macros.
|
||||
export default function Gallery({
|
||||
product,
|
||||
onClose,
|
||||
}: {
|
||||
product: SnapshotProduct;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const locale = useLocale() as Locale;
|
||||
const name = pickText(product.name, locale);
|
||||
const media = [...product.media].sort((a, b) => a.order - b.order);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex flex-col bg-black/40 p-4 backdrop-blur-sm"
|
||||
onClick={onClose}
|
||||
>
|
||||
<div
|
||||
className="glass mx-auto flex max-h-full w-full max-w-lg flex-col gap-4 overflow-y-auto rounded-3xl p-4"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="display text-lg font-semibold">{name}</h3>
|
||||
<button onClick={onClose} className="glass-pill rounded-full px-3 py-1">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex snap-x gap-3 overflow-x-auto no-scrollbar">
|
||||
{media.length === 0 && (
|
||||
<div className="flex h-56 w-full items-center justify-center text-5xl">🍽️</div>
|
||||
)}
|
||||
{media.map((m, i) =>
|
||||
m.type === 'video' ? (
|
||||
// eslint-disable-next-line jsx-a11y/media-has-caption
|
||||
<video
|
||||
key={i}
|
||||
src={m.path}
|
||||
controls
|
||||
playsInline
|
||||
className="h-56 w-full shrink-0 snap-center rounded-2xl object-cover"
|
||||
/>
|
||||
) : (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
key={i}
|
||||
src={m.path}
|
||||
alt={`${name} ${i + 1}`}
|
||||
className="h-56 w-full shrink-0 snap-center rounded-2xl object-cover"
|
||||
/>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
|
||||
<MacrosBack macros={product.macros} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { MACRO_COLORS, MACRO_KEYS } from '@/lib/macros';
|
||||
|
||||
// Collapsible accessible legend for the universal macro color code.
|
||||
export default function MacroLegend() {
|
||||
const t = useTranslations('macros');
|
||||
const tm = useTranslations('menu');
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="glass rounded-2xl px-4 py-3">
|
||||
<button
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
className="flex w-full items-center justify-between text-sm font-medium"
|
||||
aria-expanded={open}
|
||||
>
|
||||
<span>{tm('macroLegend')}</span>
|
||||
<span className={`transition-transform ${open ? 'rotate-180' : ''}`}>⌄</span>
|
||||
</button>
|
||||
{open && (
|
||||
<ul className="mt-3 grid grid-cols-2 gap-2">
|
||||
{MACRO_KEYS.map((key) => (
|
||||
<li key={key} className="flex items-center gap-2 text-sm">
|
||||
<span
|
||||
className="h-3 w-3 rounded-full"
|
||||
style={{ background: MACRO_COLORS[key] }}
|
||||
aria-hidden
|
||||
/>
|
||||
<span className="text-[var(--text)]/80">{t(key)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
'use client';
|
||||
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { MACRO_COLORS, MACRO_KEYS, MACRO_UNIT } from '@/lib/macros';
|
||||
import type { Macros } from '@/lib/types';
|
||||
|
||||
export default function MacrosBack({ macros }: { macros: Macros }) {
|
||||
const t = useTranslations('macros');
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{MACRO_KEYS.map((key) => {
|
||||
const value = macros[key];
|
||||
return (
|
||||
<div key={key} className="glass-soft flex items-center gap-2 rounded-xl px-3 py-2">
|
||||
<span
|
||||
className="h-3 w-3 shrink-0 rounded-full"
|
||||
style={{ background: MACRO_COLORS[key] }}
|
||||
aria-hidden
|
||||
/>
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] leading-tight text-[var(--text)]/60">{t(key)}</div>
|
||||
<div className="text-sm font-semibold" style={{ color: MACRO_COLORS[key] }}>
|
||||
{value != null ? `${value}${MACRO_UNIT[key] === 'g' ? ' g' : ''}` : '—'}
|
||||
{key === 'kcal' && value != null ? ' kcal' : ''}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
'use client';
|
||||
|
||||
import type { MediaItem } from '@/lib/types';
|
||||
|
||||
// Renders the first media item as a thumbnail (image or muted video poster).
|
||||
export default function MediaThumb({
|
||||
media,
|
||||
alt,
|
||||
className = '',
|
||||
}: {
|
||||
media?: MediaItem;
|
||||
alt: string;
|
||||
className?: string;
|
||||
}) {
|
||||
if (!media) {
|
||||
return (
|
||||
<div
|
||||
className={`flex items-center justify-center bg-gradient-to-br from-white/40 to-white/10 text-3xl ${className}`}
|
||||
aria-hidden
|
||||
>
|
||||
🍽️
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (media.type === 'video') {
|
||||
return (
|
||||
// eslint-disable-next-line jsx-a11y/media-has-caption
|
||||
<video
|
||||
src={media.path}
|
||||
className={`object-cover ${className}`}
|
||||
muted
|
||||
loop
|
||||
playsInline
|
||||
preload="metadata"
|
||||
/>
|
||||
);
|
||||
}
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
return <img src={media.path} alt={alt} className={`object-cover ${className}`} loading="lazy" />;
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo, useRef, useState } from 'react';
|
||||
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 DishCard from './DishCard';
|
||||
import MacroLegend from './MacroLegend';
|
||||
import Gallery from './Gallery';
|
||||
import AiConsultant from './AiConsultant';
|
||||
|
||||
type CartLine = { product: SnapshotProduct; qty: number };
|
||||
|
||||
export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: string }) {
|
||||
const locale = useLocale() as Locale;
|
||||
const t = useTranslations('menu');
|
||||
const sections = useMemo(
|
||||
() =>
|
||||
[...menu.sections]
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map((s) => ({
|
||||
...s,
|
||||
products: s.products.filter((p) => p.isActive),
|
||||
})),
|
||||
[menu.sections],
|
||||
);
|
||||
|
||||
const [activeSection, setActiveSection] = useState(sections[0]?.id ?? '');
|
||||
const [gallery, setGallery] = useState<SnapshotProduct | null>(null);
|
||||
const [aiOpen, setAiOpen] = useState(false);
|
||||
const [actionsOpen, setActionsOpen] = useState(false);
|
||||
const [cart, setCart] = useState<CartLine[]>([]);
|
||||
const [orderOpen, setOrderOpen] = useState(false);
|
||||
const [waiterOpen, setWaiterOpen] = useState(false);
|
||||
const [toast, setToast] = useState<string | null>(null);
|
||||
const sectionRefs = useRef<Record<string, HTMLElement | null>>({});
|
||||
|
||||
const ordersEnabled = menu.restaurant.ordersEnabled;
|
||||
|
||||
function scrollToSection(id: string) {
|
||||
setActiveSection(id);
|
||||
sectionRefs.current[id]?.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
}
|
||||
|
||||
function addToCart(p: SnapshotProduct) {
|
||||
setCart((prev) => {
|
||||
const existing = prev.find((l) => l.product.id === p.id);
|
||||
if (existing) return prev.map((l) => (l.product.id === p.id ? { ...l, qty: l.qty + 1 } : l));
|
||||
return [...prev, { product: p, qty: 1 }];
|
||||
});
|
||||
showToast('+1');
|
||||
}
|
||||
|
||||
function showToast(msg: string) {
|
||||
setToast(msg);
|
||||
setTimeout(() => setToast(null), 2200);
|
||||
}
|
||||
|
||||
const cartCount = cart.reduce((n, l) => n + l.qty, 0);
|
||||
|
||||
return (
|
||||
<div className="mx-auto min-h-screen max-w-2xl px-4 pb-32 pt-5">
|
||||
{/* 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>
|
||||
|
||||
{/* Section tabs */}
|
||||
{sections.length > 0 && (
|
||||
<nav className="sticky top-2 z-20 -mx-1 mb-4 flex gap-2 overflow-x-auto px-1 py-1 no-scrollbar">
|
||||
{sections.map((s) => (
|
||||
<button
|
||||
key={s.id}
|
||||
onClick={() => scrollToSection(s.id)}
|
||||
className={`glass-pill shrink-0 rounded-full px-4 py-2 text-sm font-medium transition ${
|
||||
activeSection === s.id ? 'ring-2 ring-[var(--accent)]/40' : ''
|
||||
}`}
|
||||
>
|
||||
{pickText(s.name, locale)}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
)}
|
||||
|
||||
<div className="mb-4">
|
||||
<MacroLegend />
|
||||
</div>
|
||||
|
||||
{/* Sections */}
|
||||
{sections.map((s) => (
|
||||
<section
|
||||
key={s.id}
|
||||
ref={(el) => {
|
||||
sectionRefs.current[s.id] = el;
|
||||
}}
|
||||
className="mb-8 scroll-mt-20"
|
||||
>
|
||||
<h2 className="display mb-3 text-xl font-semibold">{pickText(s.name, locale)}</h2>
|
||||
{s.products.length === 0 ? (
|
||||
<p className="text-sm text-[var(--text)]/50">{t('empty')}</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
{s.products.map((p, i) => (
|
||||
<DishCard
|
||||
key={p.id}
|
||||
product={p}
|
||||
index={i}
|
||||
onOpenGallery={setGallery}
|
||||
onAdd={ordersEnabled ? addToCart : undefined}
|
||||
ordersEnabled={ordersEnabled}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
))}
|
||||
|
||||
{/* Floating actions */}
|
||||
<div className="fixed bottom-5 left-1/2 z-30 flex -translate-x-1/2 flex-col items-center gap-3">
|
||||
{actionsOpen && (
|
||||
<div className="animate-spawn flex flex-col items-stretch gap-2">
|
||||
{ordersEnabled && (
|
||||
<button
|
||||
onClick={() => {
|
||||
setOrderOpen(true);
|
||||
setActionsOpen(false);
|
||||
}}
|
||||
className="glass rounded-full px-5 py-3 text-sm font-medium"
|
||||
>
|
||||
{t('placeOrder')} {cartCount > 0 && `(${cartCount})`}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => {
|
||||
setWaiterOpen(true);
|
||||
setActionsOpen(false);
|
||||
}}
|
||||
className="glass rounded-full px-5 py-3 text-sm font-medium"
|
||||
>
|
||||
{t('callWaiter')}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
setActionsOpen(false);
|
||||
}}
|
||||
className="glass rounded-full px-5 py-3 text-sm font-medium"
|
||||
>
|
||||
{t('viewFull')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => setAiOpen(true)}
|
||||
className="glass rounded-full px-5 py-3 text-sm font-semibold shadow-lg"
|
||||
>
|
||||
✨ {t('askAi')}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActionsOpen((o) => !o)}
|
||||
className="flex h-12 w-12 items-center justify-center rounded-full bg-[var(--accent)] text-2xl text-white shadow-lg transition"
|
||||
aria-label={t('actions')}
|
||||
>
|
||||
<span className={`transition-transform ${actionsOpen ? 'rotate-45' : ''}`}>+</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Modals */}
|
||||
{gallery && <Gallery product={gallery} onClose={() => setGallery(null)} />}
|
||||
{aiOpen && <AiConsultant slug={slug} onClose={() => setAiOpen(false)} />}
|
||||
{orderOpen && (
|
||||
<OrderPanel
|
||||
slug={slug}
|
||||
cart={cart}
|
||||
setCart={setCart}
|
||||
onClose={() => setOrderOpen(false)}
|
||||
onSent={() => {
|
||||
setCart([]);
|
||||
setOrderOpen(false);
|
||||
showToast(t('orderSent'));
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{waiterOpen && (
|
||||
<WaiterPanel
|
||||
slug={slug}
|
||||
onClose={() => setWaiterOpen(false)}
|
||||
onSent={() => {
|
||||
setWaiterOpen(false);
|
||||
showToast(t('waiterCalled'));
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{toast && (
|
||||
<div className="animate-spawn fixed bottom-24 left-1/2 z-50 -translate-x-1/2 rounded-full bg-[var(--text)] px-5 py-2 text-sm text-white shadow-lg">
|
||||
{toast}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TableInput({ value, onChange }: { value: string; onChange: (v: string) => void }) {
|
||||
const t = useTranslations('menu');
|
||||
return (
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
inputMode="numeric"
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder={t('tableNumber')}
|
||||
className="glass-soft w-full rounded-2xl px-4 py-3 text-center text-lg outline-none"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function OrderPanel({
|
||||
slug,
|
||||
cart,
|
||||
setCart,
|
||||
onClose,
|
||||
onSent,
|
||||
}: {
|
||||
slug: string;
|
||||
cart: CartLine[];
|
||||
setCart: React.Dispatch<React.SetStateAction<CartLine[]>>;
|
||||
onClose: () => void;
|
||||
onSent: () => void;
|
||||
}) {
|
||||
const locale = useLocale() as Locale;
|
||||
const t = useTranslations('menu');
|
||||
const [table, setTable] = useState('');
|
||||
const [sending, setSending] = useState(false);
|
||||
|
||||
function setQty(id: string, delta: number) {
|
||||
setCart((prev) =>
|
||||
prev
|
||||
.map((l) => (l.product.id === id ? { ...l, qty: l.qty + delta } : l))
|
||||
.filter((l) => l.qty > 0),
|
||||
);
|
||||
}
|
||||
|
||||
async function send() {
|
||||
if (!table || cart.length === 0 || sending) return;
|
||||
setSending(true);
|
||||
try {
|
||||
await fetch(`/api/${slug}/order`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
tableNumber: Number(table),
|
||||
items: cart.map((l) => ({
|
||||
productId: l.product.id,
|
||||
name: pickText(l.product.name, locale),
|
||||
qty: l.qty,
|
||||
})),
|
||||
}),
|
||||
});
|
||||
onSent();
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet title={t('yourOrder')} onClose={onClose}>
|
||||
<div className="flex flex-col gap-2">
|
||||
{cart.length === 0 && <p className="text-sm text-[var(--text)]/60">—</p>}
|
||||
{cart.map((l) => (
|
||||
<div key={l.product.id} className="glass-soft flex items-center gap-2 rounded-2xl px-3 py-2">
|
||||
<span className="flex-1 text-sm">{pickText(l.product.name, locale)}</span>
|
||||
<button onClick={() => setQty(l.product.id, -1)} className="px-2 text-lg">
|
||||
−
|
||||
</button>
|
||||
<span className="w-5 text-center">{l.qty}</span>
|
||||
<button onClick={() => setQty(l.product.id, 1)} className="px-2 text-lg">
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<TableInput value={table} onChange={setTable} />
|
||||
<button
|
||||
onClick={send}
|
||||
disabled={!table || cart.length === 0 || sending}
|
||||
className="rounded-2xl bg-[var(--accent)] py-3 font-medium text-white disabled:opacity-50"
|
||||
>
|
||||
{t('send')}
|
||||
</button>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
function WaiterPanel({
|
||||
slug,
|
||||
onClose,
|
||||
onSent,
|
||||
}: {
|
||||
slug: string;
|
||||
onClose: () => void;
|
||||
onSent: () => void;
|
||||
}) {
|
||||
const t = useTranslations('menu');
|
||||
const [table, setTable] = useState('');
|
||||
const [sending, setSending] = useState(false);
|
||||
|
||||
async function send() {
|
||||
if (!table || sending) return;
|
||||
setSending(true);
|
||||
try {
|
||||
await fetch(`/api/${slug}/call-waiter`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ tableNumber: Number(table) }),
|
||||
});
|
||||
onSent();
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet title={t('callWaiter')} onClose={onClose}>
|
||||
<TableInput value={table} onChange={setTable} />
|
||||
<button
|
||||
onClick={send}
|
||||
disabled={!table || sending}
|
||||
className="rounded-2xl bg-[var(--accent)] py-3 font-medium text-white disabled:opacity-50"
|
||||
>
|
||||
{t('send')}
|
||||
</button>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
function Sheet({
|
||||
title,
|
||||
onClose,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
onClose: () => void;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-end justify-center bg-black/40 p-3 backdrop-blur-sm sm:items-center">
|
||||
<div className="glass flex w-full max-w-md flex-col gap-3 rounded-3xl p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="display text-lg font-semibold">{title}</h3>
|
||||
<button onClick={onClose} className="glass-pill rounded-full px-3 py-1">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export const locales = ['es', 'en'] as const;
|
||||
export type Locale = (typeof locales)[number];
|
||||
export const defaultLocale: Locale = 'es';
|
||||
export const LOCALE_COOKIE = 'smartmenu_locale';
|
||||
|
||||
export function isLocale(value: string | undefined | null): value is Locale {
|
||||
return !!value && (locales as readonly string[]).includes(value);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { getRequestConfig } from 'next-intl/server';
|
||||
import { cookies } from 'next/headers';
|
||||
import { defaultLocale, isLocale, LOCALE_COOKIE } from './config';
|
||||
|
||||
// next-intl without i18n routing: locale comes from a cookie so the public
|
||||
// menu can switch ES/EN via a floating toggle without changing the URL.
|
||||
export default getRequestConfig(async () => {
|
||||
const cookieLocale = cookies().get(LOCALE_COOKIE)?.value;
|
||||
const locale = isLocale(cookieLocale) ? cookieLocale : defaultLocale;
|
||||
|
||||
return {
|
||||
locale,
|
||||
messages: (await import(`../../messages/${locale}.json`)).default,
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import Anthropic from '@anthropic-ai/sdk';
|
||||
|
||||
// Claude Haiku — cheapest model that works well for translation and the consultant.
|
||||
export const HAIKU_MODEL = 'claude-haiku-4-5';
|
||||
|
||||
let client: Anthropic | null = null;
|
||||
|
||||
export function getAnthropic(): Anthropic {
|
||||
if (!process.env.ANTHROPIC_API_KEY) {
|
||||
throw new Error('ANTHROPIC_API_KEY is not set');
|
||||
}
|
||||
if (!client) {
|
||||
client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
|
||||
}
|
||||
return client;
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { SignJWT, jwtVerify } from 'jose';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { cookies } from 'next/headers';
|
||||
import crypto from 'crypto';
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'dev-insecure-secret-change-me';
|
||||
const key = new TextEncoder().encode(JWT_SECRET);
|
||||
|
||||
export type EditorSession = { slug: string; restaurantId: string };
|
||||
|
||||
export function editorCookieName(slug: string) {
|
||||
return `smartmenu_editor_${slug}`;
|
||||
}
|
||||
|
||||
export async function signEditorToken(session: EditorSession): Promise<string> {
|
||||
return new SignJWT(session)
|
||||
.setProtectedHeader({ alg: 'HS256' })
|
||||
.setIssuedAt()
|
||||
.setExpirationTime('7d')
|
||||
.sign(key);
|
||||
}
|
||||
|
||||
export async function verifyEditorToken(token: string): Promise<EditorSession | null> {
|
||||
try {
|
||||
const { payload } = await jwtVerify(token, key);
|
||||
return { slug: payload.slug as string, restaurantId: payload.restaurantId as string };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getEditorSession(slug: string): Promise<EditorSession | null> {
|
||||
const token = cookies().get(editorCookieName(slug))?.value;
|
||||
if (!token) return null;
|
||||
const session = await verifyEditorToken(token);
|
||||
if (!session || session.slug !== slug) return null;
|
||||
return session;
|
||||
}
|
||||
|
||||
export async function hashPassword(password: string): Promise<string> {
|
||||
return bcrypt.hash(password, 10);
|
||||
}
|
||||
|
||||
export async function verifyPassword(password: string, hashed: string): Promise<boolean> {
|
||||
return bcrypt.compare(password, hashed);
|
||||
}
|
||||
|
||||
export function generateSecret(bytes = 32): string {
|
||||
return crypto.randomBytes(bytes).toString('base64url');
|
||||
}
|
||||
|
||||
export function generatePassword(): string {
|
||||
return crypto.randomBytes(9).toString('base64url');
|
||||
}
|
||||
|
||||
// Superadmin session (env-based credentials).
|
||||
const ADMIN_COOKIE = 'smartmenu_admin';
|
||||
|
||||
export async function signAdminToken(): Promise<string> {
|
||||
return new SignJWT({ role: 'superadmin' })
|
||||
.setProtectedHeader({ alg: 'HS256' })
|
||||
.setIssuedAt()
|
||||
.setExpirationTime('1d')
|
||||
.sign(key);
|
||||
}
|
||||
|
||||
export async function isAdminAuthed(): Promise<boolean> {
|
||||
const token = cookies().get(ADMIN_COOKIE)?.value;
|
||||
if (!token) return false;
|
||||
try {
|
||||
const { payload } = await jwtVerify(token, key);
|
||||
return payload.role === 'superadmin';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function checkAdminCredentials(user: string, password: string): boolean {
|
||||
return (
|
||||
!!process.env.SUPERADMIN_USER &&
|
||||
user === process.env.SUPERADMIN_USER &&
|
||||
password === process.env.SUPERADMIN_PASSWORD
|
||||
);
|
||||
}
|
||||
|
||||
export { ADMIN_COOKIE };
|
||||
@@ -0,0 +1,17 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from './prisma';
|
||||
import { getEditorSession } from './auth';
|
||||
|
||||
// Guard for editor API routes: requires a valid JWT session for the slug.
|
||||
// Returns either the restaurant or a 401 response to return directly.
|
||||
export async function requireEditor(slug: string) {
|
||||
const session = await getEditorSession(slug);
|
||||
if (!session) {
|
||||
return { error: NextResponse.json({ error: 'unauthorized' }, { status: 401 }) } as const;
|
||||
}
|
||||
const restaurant = await prisma.restaurant.findUnique({ where: { slug } });
|
||||
if (!restaurant || restaurant.id !== session.restaurantId) {
|
||||
return { error: NextResponse.json({ error: 'unauthorized' }, { status: 401 }) } as const;
|
||||
}
|
||||
return { restaurant } as const;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Universal macro color code — FIXED across all restaurants (product standard).
|
||||
// Diners learn it once and recognize it in any menu. Never make this configurable.
|
||||
export const MACRO_COLORS = {
|
||||
protein: '#C2410C', // terracotta
|
||||
carbs: '#B45309', // toasted amber
|
||||
sugar: '#BE185D', // magenta
|
||||
fat: '#CA8A04', // gold
|
||||
fiber: '#15803D', // green
|
||||
kcal: '#1D4ED8', // blue
|
||||
} as const;
|
||||
|
||||
export type MacroKey = keyof typeof MACRO_COLORS;
|
||||
|
||||
// kcal is shown but isn't a gram unit.
|
||||
export const MACRO_KEYS: MacroKey[] = ['protein', 'carbs', 'sugar', 'fat', 'fiber', 'kcal'];
|
||||
|
||||
export const MACRO_UNIT: Record<MacroKey, string> = {
|
||||
protein: 'g',
|
||||
carbs: 'g',
|
||||
sugar: 'g',
|
||||
fat: 'g',
|
||||
fiber: 'g',
|
||||
kcal: 'kcal',
|
||||
};
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
import { prisma } from './prisma';
|
||||
import type {
|
||||
MenuSnapshot,
|
||||
SnapshotSection,
|
||||
SnapshotProduct,
|
||||
LocalizedText,
|
||||
Macros,
|
||||
MediaItem,
|
||||
TranslationStatus,
|
||||
Palette,
|
||||
} from './types';
|
||||
import type { Locale } from '@/i18n/config';
|
||||
|
||||
const MAX_VERSIONS = 5;
|
||||
|
||||
// Build a complete snapshot of the current DRAFT (Section + Product tables).
|
||||
export async function buildSnapshot(restaurantId: string): Promise<MenuSnapshot> {
|
||||
const restaurant = await prisma.restaurant.findUniqueOrThrow({
|
||||
where: { id: restaurantId },
|
||||
});
|
||||
|
||||
const sections = await prisma.section.findMany({
|
||||
where: { restaurantId },
|
||||
orderBy: { order: 'asc' },
|
||||
include: { products: { orderBy: { order: 'asc' } } },
|
||||
});
|
||||
|
||||
return {
|
||||
restaurant: {
|
||||
name: restaurant.name,
|
||||
slug: restaurant.slug,
|
||||
palette: (restaurant.palette as Palette) ?? {},
|
||||
ordersEnabled: restaurant.ordersEnabled,
|
||||
defaultLocale: restaurant.defaultLocale as Locale,
|
||||
},
|
||||
sections: sections.map(
|
||||
(s): SnapshotSection => ({
|
||||
id: s.id,
|
||||
name: s.name as LocalizedText,
|
||||
order: s.order,
|
||||
products: s.products.map(
|
||||
(p): SnapshotProduct => ({
|
||||
id: p.id,
|
||||
name: p.name as LocalizedText,
|
||||
description: p.description as LocalizedText,
|
||||
price: Number(p.price),
|
||||
isActive: p.isActive,
|
||||
allergens: p.allergens,
|
||||
dietTags: p.dietTags,
|
||||
macros: p.macros as Macros,
|
||||
media: (p.media as MediaItem[]) ?? [],
|
||||
translationStatus: p.translationStatus as TranslationStatus,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
// Create a published version from the current draft, keeping max 5 versions.
|
||||
export async function publishVersion(
|
||||
restaurantId: string,
|
||||
versionName: string,
|
||||
createdBy?: string,
|
||||
): Promise<{ id: string; versionName: string }> {
|
||||
const snapshot = await buildSnapshot(restaurantId);
|
||||
|
||||
const version = await prisma.menuVersion.create({
|
||||
data: {
|
||||
restaurantId,
|
||||
versionName,
|
||||
snapshot: snapshot as unknown as object,
|
||||
createdBy,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.restaurant.update({
|
||||
where: { id: restaurantId },
|
||||
data: { publishedVersionId: version.id },
|
||||
});
|
||||
|
||||
// Prune to the most recent MAX_VERSIONS, never deleting the published one.
|
||||
const all = await prisma.menuVersion.findMany({
|
||||
where: { restaurantId },
|
||||
orderBy: { publishedAt: 'desc' },
|
||||
select: { id: true },
|
||||
});
|
||||
const toDelete = all.slice(MAX_VERSIONS).map((v) => v.id);
|
||||
if (toDelete.length) {
|
||||
await prisma.menuVersion.deleteMany({
|
||||
where: { id: { in: toDelete }, NOT: { publishedFor: { isNot: null } } },
|
||||
});
|
||||
}
|
||||
|
||||
return { id: version.id, versionName: version.versionName };
|
||||
}
|
||||
|
||||
// Overwrite the draft (Section + Product) from a stored snapshot.
|
||||
export async function restoreSnapshotToDraft(
|
||||
restaurantId: string,
|
||||
snapshot: MenuSnapshot,
|
||||
): Promise<void> {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.product.deleteMany({ where: { restaurantId } });
|
||||
await tx.section.deleteMany({ where: { restaurantId } });
|
||||
|
||||
for (const s of snapshot.sections) {
|
||||
const section = await tx.section.create({
|
||||
data: {
|
||||
restaurantId,
|
||||
name: s.name as object,
|
||||
order: s.order,
|
||||
},
|
||||
});
|
||||
for (const p of s.products) {
|
||||
await tx.product.create({
|
||||
data: {
|
||||
sectionId: section.id,
|
||||
restaurantId,
|
||||
name: p.name as object,
|
||||
description: p.description as object,
|
||||
price: p.price,
|
||||
isActive: p.isActive,
|
||||
allergens: p.allergens,
|
||||
dietTags: p.dietTags,
|
||||
macros: p.macros as object,
|
||||
media: p.media as object,
|
||||
translationStatus: p.translationStatus as object,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export { MAX_VERSIONS };
|
||||
@@ -0,0 +1,31 @@
|
||||
// In-process pub/sub for realtime orders over SSE.
|
||||
// One Next.js instance per Coolify deploy makes this sufficient; swap for Redis
|
||||
// pub/sub if the app is ever scaled horizontally.
|
||||
type Listener = (event: { type: string; data: unknown }) => void;
|
||||
|
||||
const channels = new Map<string, Set<Listener>>();
|
||||
|
||||
function globalBus(): Map<string, Set<Listener>> {
|
||||
const g = globalThis as unknown as { __ordersBus?: Map<string, Set<Listener>> };
|
||||
if (!g.__ordersBus) g.__ordersBus = channels;
|
||||
return g.__ordersBus;
|
||||
}
|
||||
|
||||
export function subscribe(slug: string, listener: Listener): () => void {
|
||||
const bus = globalBus();
|
||||
let set = bus.get(slug);
|
||||
if (!set) {
|
||||
set = new Set();
|
||||
bus.set(slug, set);
|
||||
}
|
||||
set.add(listener);
|
||||
return () => {
|
||||
set?.delete(listener);
|
||||
if (set && set.size === 0) bus.delete(slug);
|
||||
};
|
||||
}
|
||||
|
||||
export function publish(slug: string, event: { type: string; data: unknown }): void {
|
||||
const bus = globalBus();
|
||||
bus.get(slug)?.forEach((l) => l(event));
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { Palette } from './types';
|
||||
|
||||
// Elegant glass presets the restaurant can pick from (or customize).
|
||||
export const PALETTE_PRESETS: { id: string; label: string; palette: Palette }[] = [
|
||||
{
|
||||
id: 'sand',
|
||||
label: 'Arena',
|
||||
palette: { background: '#f4f1ec', surface: 'rgba(255,255,255,0.55)', accent: '#b45309', text: '#2a2520', tab: 'rgba(255,255,255,0.45)' },
|
||||
},
|
||||
{
|
||||
id: 'sage',
|
||||
label: 'Salvia',
|
||||
palette: { background: '#eef2ec', surface: 'rgba(255,255,255,0.5)', accent: '#3f6212', text: '#26301f', tab: 'rgba(255,255,255,0.5)' },
|
||||
},
|
||||
{
|
||||
id: 'blush',
|
||||
label: 'Rubor',
|
||||
palette: { background: '#f6eef0', surface: 'rgba(255,255,255,0.55)', accent: '#be185d', text: '#33232a', tab: 'rgba(255,255,255,0.5)' },
|
||||
},
|
||||
{
|
||||
id: 'sky',
|
||||
label: 'Cielo',
|
||||
palette: { background: '#eaf1f7', surface: 'rgba(255,255,255,0.55)', accent: '#1d4ed8', text: '#1f2a37', tab: 'rgba(255,255,255,0.5)' },
|
||||
},
|
||||
{
|
||||
id: 'graphite',
|
||||
label: 'Grafito',
|
||||
palette: { background: '#edeef0', surface: 'rgba(255,255,255,0.6)', accent: '#334155', text: '#1f2937', tab: 'rgba(255,255,255,0.55)' },
|
||||
},
|
||||
];
|
||||
|
||||
const DEFAULT = PALETTE_PRESETS[0].palette;
|
||||
|
||||
// Build a CSS variable string from a palette, deriving a darker bottom gradient.
|
||||
export function paletteToCssVars(palette?: Palette): string {
|
||||
const p = { ...DEFAULT, ...(palette ?? {}) };
|
||||
return [
|
||||
`--bg:${p.background};`,
|
||||
`--bg-2:${shade(p.background!, -8)};`,
|
||||
`--surface:${p.surface};`,
|
||||
`--accent:${p.accent};`,
|
||||
`--text:${p.text};`,
|
||||
`--tab:${p.tab};`,
|
||||
].join('');
|
||||
}
|
||||
|
||||
// Lighten/darken a hex color by a percentage (-100..100).
|
||||
function shade(hex: string, percent: number): string {
|
||||
const m = hex.replace('#', '');
|
||||
if (m.length !== 6) return hex;
|
||||
const num = parseInt(m, 16);
|
||||
const amt = Math.round(2.55 * percent);
|
||||
const r = clamp((num >> 16) + amt);
|
||||
const g = clamp(((num >> 8) & 0xff) + amt);
|
||||
const b = clamp((num & 0xff) + amt);
|
||||
return `#${((r << 16) | (g << 8) | b).toString(16).padStart(6, '0')}`;
|
||||
}
|
||||
|
||||
function clamp(v: number): number {
|
||||
return Math.max(0, Math.min(255, v));
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };
|
||||
|
||||
export const prisma =
|
||||
globalForPrisma.prisma ??
|
||||
new PrismaClient({
|
||||
log: process.env.NODE_ENV === 'development' ? ['error', 'warn'] : ['error'],
|
||||
});
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { LocalizedText } from './types';
|
||||
import type { Locale } from '@/i18n/config';
|
||||
|
||||
// Pick the best available text for a locale, falling back to the other one.
|
||||
export function pickText(text: LocalizedText | undefined, locale: Locale): string {
|
||||
if (!text) return '';
|
||||
const primary = text[locale];
|
||||
if (primary && primary.trim()) return primary;
|
||||
const other = locale === 'es' ? text.en : text.es;
|
||||
return other ?? '';
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { Locale } from '@/i18n/config';
|
||||
|
||||
export type LocalizedText = { es?: string; en?: string };
|
||||
|
||||
export type MediaItem = {
|
||||
type: 'image' | 'video';
|
||||
path: string;
|
||||
order: number;
|
||||
};
|
||||
|
||||
export type Macros = {
|
||||
protein?: number;
|
||||
carbs?: number;
|
||||
sugar?: number;
|
||||
fat?: number;
|
||||
fiber?: number;
|
||||
kcal?: number;
|
||||
};
|
||||
|
||||
export type TranslationStatus = { en?: 'auto' | 'reviewed' };
|
||||
|
||||
export type Palette = {
|
||||
background?: string;
|
||||
surface?: string;
|
||||
accent?: string;
|
||||
text?: string;
|
||||
tab?: string;
|
||||
};
|
||||
|
||||
// Shape stored inside MenuVersion.snapshot and served to the public menu.
|
||||
export type MenuSnapshot = {
|
||||
restaurant: {
|
||||
name: string;
|
||||
slug: string;
|
||||
palette: Palette;
|
||||
ordersEnabled: boolean;
|
||||
defaultLocale: Locale;
|
||||
};
|
||||
sections: SnapshotSection[];
|
||||
};
|
||||
|
||||
export type SnapshotSection = {
|
||||
id: string;
|
||||
name: LocalizedText;
|
||||
order: number;
|
||||
products: SnapshotProduct[];
|
||||
};
|
||||
|
||||
export type SnapshotProduct = {
|
||||
id: string;
|
||||
name: LocalizedText;
|
||||
description: LocalizedText;
|
||||
price: number;
|
||||
isActive: boolean;
|
||||
allergens: string[];
|
||||
dietTags: string[];
|
||||
macros: Macros;
|
||||
media: MediaItem[];
|
||||
translationStatus: TranslationStatus;
|
||||
};
|
||||
|
||||
export type OrderItem = { productId: string; name: string; qty: number };
|
||||
@@ -0,0 +1,45 @@
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import crypto from 'crypto';
|
||||
|
||||
export const UPLOAD_DIR = process.env.UPLOAD_DIR || '/data/uploads';
|
||||
|
||||
const IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/avif', 'image/gif'];
|
||||
const VIDEO_TYPES = ['video/mp4', 'video/webm', 'video/quicktime'];
|
||||
|
||||
export function mediaTypeFor(mime: string): 'image' | 'video' | null {
|
||||
if (IMAGE_TYPES.includes(mime)) return 'image';
|
||||
if (VIDEO_TYPES.includes(mime)) return 'video';
|
||||
return null;
|
||||
}
|
||||
|
||||
const EXT: Record<string, string> = {
|
||||
'image/jpeg': 'jpg',
|
||||
'image/png': 'png',
|
||||
'image/webp': 'webp',
|
||||
'image/avif': 'avif',
|
||||
'image/gif': 'gif',
|
||||
'video/mp4': 'mp4',
|
||||
'video/webm': 'webm',
|
||||
'video/quicktime': 'mov',
|
||||
};
|
||||
|
||||
// Saves a file under /data/uploads/{slug}/ and returns its public path (served
|
||||
// via the /api/uploads/[...] route).
|
||||
export async function saveUpload(
|
||||
slug: string,
|
||||
file: File,
|
||||
): Promise<{ path: string; type: 'image' | 'video' }> {
|
||||
const type = mediaTypeFor(file.type);
|
||||
if (!type) throw new Error('Unsupported file type');
|
||||
|
||||
const dir = path.join(UPLOAD_DIR, slug);
|
||||
await fs.mkdir(dir, { recursive: true });
|
||||
|
||||
const ext = EXT[file.type] || 'bin';
|
||||
const filename = `${Date.now()}-${crypto.randomBytes(6).toString('hex')}.${ext}`;
|
||||
const buffer = Buffer.from(await file.arrayBuffer());
|
||||
await fs.writeFile(path.join(dir, filename), buffer);
|
||||
|
||||
return { path: `/api/uploads/${slug}/${filename}`, type };
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import type { Config } from 'tailwindcss';
|
||||
|
||||
const config: Config = {
|
||||
content: [
|
||||
'./src/**/*.{js,ts,jsx,tsx,mdx}',
|
||||
],
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
display: ['var(--font-fraunces)', 'Georgia', 'serif'],
|
||||
body: ['var(--font-inter)', 'system-ui', 'sans-serif'],
|
||||
},
|
||||
colors: {
|
||||
// Universal, non-configurable macro color code (product standard).
|
||||
macro: {
|
||||
protein: '#C2410C',
|
||||
carbs: '#B45309',
|
||||
sugar: '#BE185D',
|
||||
fat: '#CA8A04',
|
||||
fiber: '#15803D',
|
||||
kcal: '#1D4ED8',
|
||||
},
|
||||
},
|
||||
backdropBlur: {
|
||||
xs: '2px',
|
||||
},
|
||||
keyframes: {
|
||||
'fade-up': {
|
||||
'0%': { opacity: '0', transform: 'translateY(16px)' },
|
||||
'100%': { opacity: '1', transform: 'translateY(0)' },
|
||||
},
|
||||
'spawn': {
|
||||
'0%': { opacity: '0', transform: 'scale(0.92) translateY(8px)' },
|
||||
'100%': { opacity: '1', transform: 'scale(1) translateY(0)' },
|
||||
},
|
||||
'pulse-dot': {
|
||||
'0%, 100%': { opacity: '1', transform: 'scale(1)' },
|
||||
'50%': { opacity: '0.4', transform: 'scale(0.85)' },
|
||||
},
|
||||
},
|
||||
animation: {
|
||||
'fade-up': 'fade-up 0.5s cubic-bezier(0.22, 1, 0.36, 1) both',
|
||||
'spawn': 'spawn 0.4s cubic-bezier(0.22, 1, 0.36, 1) both',
|
||||
'pulse-dot': 'pulse-dot 1.4s ease-in-out infinite',
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [],
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2021",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "preserve",
|
||||
"incremental": true,
|
||||
"plugins": [{ "name": "next" }],
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
Reference in new issue
Block a user