From 112e95dc2899ba6e415f71e54da60bfca03e4451 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorem=20Ju=C3=A1rez?= Date: Sat, 13 Jun 2026 20:43:06 -0600 Subject: [PATCH] =?UTF-8?q?Add=20AI=20smart=20menu=20import=20(Cargar=20me?= =?UTF-8?q?n=C3=BA)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Import a menu from PDF, photo, Excel/CSV, web link, or pasted text and turn it into draft sections + products with Claude. - Product.aiEstimated JSON flags AI-inferred macros/allergens (migration 0002) - POST /api/[slug]/import: resolves the source (vision via Sonnet for PDF/photo, Haiku for text/CSV/XLSX/web), extracts structured JSON for review only - POST /api/[slug]/import/apply: writes to the draft in add or replace mode, preserving aiEstimated flags; replace wipes the draft first - Editor: 'Cargar menú' button + glass ImportModal (method -> review -> add/replace), 'Estimado por IA — verifica' badges, verification disclaimer; ProductEditor shows the badge and clears the flag when the value is edited - Reuses anthropic.ts, upload/guard, shared extractJson (moved to lib/json.ts) - i18n labels (es/en); adds xlsx dependency for spreadsheet parsing Verified: build passes; migration applies; apply add/replace persist correctly with aiEstimated; extract validation + auth guard behave as expected. --- messages/en.json | 29 ++ messages/es.json | 29 ++ package-lock.json | 106 +++++++- package.json | 1 + .../0002_product_ai_estimated/migration.sql | 2 + prisma/schema.prisma | 1 + src/app/[slug]/editor/page.tsx | 1 + src/app/api/[slug]/ai-consult/route.ts | 11 +- src/app/api/[slug]/import/apply/route.ts | 68 +++++ src/app/api/[slug]/import/route.ts | 45 ++++ src/app/api/[slug]/products/[id]/route.ts | 1 + src/app/api/[slug]/products/route.ts | 1 + src/components/editor/CatalogTab.tsx | 21 ++ src/components/editor/ImportModal.tsx | 249 ++++++++++++++++++ src/components/editor/ProductEditor.tsx | 33 ++- src/components/editor/types.ts | 1 + src/lib/anthropic.ts | 4 + src/lib/import.ts | 223 ++++++++++++++++ src/lib/json.ts | 9 + 19 files changed, 819 insertions(+), 16 deletions(-) create mode 100644 prisma/migrations/0002_product_ai_estimated/migration.sql create mode 100644 src/app/api/[slug]/import/apply/route.ts create mode 100644 src/app/api/[slug]/import/route.ts create mode 100644 src/components/editor/ImportModal.tsx create mode 100644 src/lib/import.ts create mode 100644 src/lib/json.ts diff --git a/messages/en.json b/messages/en.json index f8bfe06..ca028be 100644 --- a/messages/en.json +++ b/messages/en.json @@ -84,6 +84,35 @@ "copied": "Copied", "paletteHint": "This does not affect the macro color code" }, + "import": { + "title": "Load menu", + "loadMenu": "Load menu", + "method": { + "file": "File", + "link": "Link", + "text": "Text" + }, + "filePrompt": "Tap to choose a file", + "fileHint": "PDF, photo of the menu, Excel or CSV", + "textPrompt": "Paste your menu text here…", + "disclaimer": "Estimates (especially allergens) are AI-generated and must be verified before publishing. Smart Menu is not responsible for unverified data.", + "extract": "Extract menu", + "extracting": "Reading your menu with AI…", + "reviewSummary": "We found {sections} sections and {products} dishes. Review them before applying.", + "estimatedBadge": "Estimated by AI — verify", + "modeAdd": "Add to my current menu", + "modeReplace": "Replace my current menu", + "replaceWarning": "This will delete your current draft sections and dishes.", + "apply": "Apply to draft", + "errors": { + "import_failed": "We couldn't read that menu. Try another file or paste the text.", + "nothing_found": "We didn't find any dishes in what you sent.", + "invalid_link": "That link isn't valid.", + "fetch_failed": "We couldn't open that link.", + "empty_text": "Paste some text first.", + "no_file": "Choose a file first." + } + }, "auth": { "login": "Log in", "username": "Username", diff --git a/messages/es.json b/messages/es.json index 1bca1c4..111d1d4 100644 --- a/messages/es.json +++ b/messages/es.json @@ -84,6 +84,35 @@ "copied": "Copiado", "paletteHint": "Esto no afecta el código de color de macros" }, + "import": { + "title": "Cargar menú", + "loadMenu": "Cargar menú", + "method": { + "file": "Archivo", + "link": "Link", + "text": "Texto" + }, + "filePrompt": "Toca para elegir un archivo", + "fileHint": "PDF, foto de la carta, Excel o CSV", + "textPrompt": "Pega aquí el texto de tu menú…", + "disclaimer": "Las estimaciones (sobre todo los alérgenos) son generadas por IA y deben verificarse antes de publicar. Smart Menu no se responsabiliza por datos no verificados.", + "extract": "Extraer menú", + "extracting": "Leyendo tu menú con IA…", + "reviewSummary": "Encontramos {sections} secciones y {products} platillos. Revísalos antes de aplicar.", + "estimatedBadge": "Estimado por IA — verifica", + "modeAdd": "Añadir a mi menú actual", + "modeReplace": "Reemplazar mi menú actual", + "replaceWarning": "Esto borrará tus secciones y platillos actuales del borrador.", + "apply": "Aplicar al borrador", + "errors": { + "import_failed": "No pudimos leer ese menú. Intenta con otro archivo o pega el texto.", + "nothing_found": "No encontramos platillos en lo que enviaste.", + "invalid_link": "El link no es válido.", + "fetch_failed": "No pudimos abrir ese link.", + "empty_text": "Pega algo de texto primero.", + "no_file": "Elige un archivo primero." + } + }, "auth": { "login": "Iniciar sesión", "username": "Usuario", diff --git a/package-lock.json b/package-lock.json index 322f0fd..734ab10 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,7 +17,8 @@ "next-intl": "^3.26.3", "qrcode": "^1.5.4", "react": "^18.3.1", - "react-dom": "^18.3.1" + "react-dom": "^18.3.1", + "xlsx": "^0.18.5" }, "devDependencies": { "@types/bcryptjs": "^2.4.6", @@ -943,6 +944,15 @@ "@types/react": "^18.0.0" } }, + "node_modules/adler-32": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.3.1.tgz", + "integrity": "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, "node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", @@ -1161,6 +1171,19 @@ ], "license": "CC-BY-4.0" }, + "node_modules/cfb": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cfb/-/cfb-1.2.2.tgz", + "integrity": "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==", + "license": "Apache-2.0", + "dependencies": { + "adler-32": "~1.3.0", + "crc-32": "~1.2.0" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/chokidar": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", @@ -1225,6 +1248,15 @@ "node": ">=6" } }, + "node_modules/codepage": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/codepage/-/codepage-1.15.0.tgz", + "integrity": "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", @@ -1253,6 +1285,18 @@ "node": ">= 6" } }, + "node_modules/crc-32": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz", + "integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==", + "license": "Apache-2.0", + "bin": { + "crc32": "bin/crc32.njs" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/cssesc": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", @@ -1449,6 +1493,15 @@ "node": ">=8" } }, + "node_modules/frac": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/frac/-/frac-1.1.2.tgz", + "integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, "node_modules/fraction.js": { "version": "5.3.4", "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz", @@ -2362,6 +2415,18 @@ "node": ">=0.10.0" } }, + "node_modules/ssf": { + "version": "0.11.2", + "resolved": "https://registry.npmjs.org/ssf/-/ssf-0.11.2.tgz", + "integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==", + "license": "Apache-2.0", + "dependencies": { + "frac": "~1.1.2" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/streamsearch": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", @@ -2693,6 +2758,24 @@ "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", "license": "ISC" }, + "node_modules/wmf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wmf/-/wmf-1.0.2.tgz", + "integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/word": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/word/-/word-0.3.0.tgz", + "integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, "node_modules/wrap-ansi": { "version": "6.2.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", @@ -2707,6 +2790,27 @@ "node": ">=8" } }, + "node_modules/xlsx": { + "version": "0.18.5", + "resolved": "https://registry.npmjs.org/xlsx/-/xlsx-0.18.5.tgz", + "integrity": "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==", + "license": "Apache-2.0", + "dependencies": { + "adler-32": "~1.3.0", + "cfb": "~1.2.1", + "codepage": "~1.15.0", + "crc-32": "~1.2.1", + "ssf": "~0.11.2", + "wmf": "~1.0.1", + "word": "~0.3.0" + }, + "bin": { + "xlsx": "bin/xlsx.njs" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/y18n": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", diff --git a/package.json b/package.json index aa4053c..143a5d2 100644 --- a/package.json +++ b/package.json @@ -24,6 +24,7 @@ "next": "14.2.21", "next-intl": "^3.26.3", "qrcode": "^1.5.4", + "xlsx": "^0.18.5", "react": "^18.3.1", "react-dom": "^18.3.1" }, diff --git a/prisma/migrations/0002_product_ai_estimated/migration.sql b/prisma/migrations/0002_product_ai_estimated/migration.sql new file mode 100644 index 0000000..024687b --- /dev/null +++ b/prisma/migrations/0002_product_ai_estimated/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "Product" ADD COLUMN "aiEstimated" JSONB NOT NULL DEFAULT '{}'; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 71d1004..65932e7 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -75,6 +75,7 @@ model Product { macros Json @default("{}") // { protein, carbs, sugar, fat, fiber, kcal } media Json @default("[]") // [{ type, path, order }] translationStatus Json @default("{}") // { en: auto|reviewed } + aiEstimated Json @default("{}") // { macros: bool, allergens: bool } — flags AI-inferred data to verify createdAt DateTime @default(now()) section Section @relation(fields: [sectionId], references: [id], onDelete: Cascade) diff --git a/src/app/[slug]/editor/page.tsx b/src/app/[slug]/editor/page.tsx index c5a6632..c9fbdbf 100644 --- a/src/app/[slug]/editor/page.tsx +++ b/src/app/[slug]/editor/page.tsx @@ -57,6 +57,7 @@ export default async function EditorPage({ macros: p.macros as Record, media: p.media as { type: 'image' | 'video'; path: string; order: number }[], translationStatus: p.translationStatus as { en?: 'auto' | 'reviewed' }, + aiEstimated: p.aiEstimated as { macros?: boolean; allergens?: boolean }, })), })), }; diff --git a/src/app/api/[slug]/ai-consult/route.ts b/src/app/api/[slug]/ai-consult/route.ts index 58cff7c..46d4f13 100644 --- a/src/app/api/[slug]/ai-consult/route.ts +++ b/src/app/api/[slug]/ai-consult/route.ts @@ -1,6 +1,7 @@ import { NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; import { getAnthropic, HAIKU_MODEL } from '@/lib/anthropic'; +import { extractJson } from '@/lib/json'; import { pickText } from '@/lib/text'; import type { Locale } from '@/i18n/config'; import type { MenuSnapshot } from '@/lib/types'; @@ -82,13 +83,3 @@ export async function POST(req: Request, { params }: { params: { slug: string } 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; -} diff --git a/src/app/api/[slug]/import/apply/route.ts b/src/app/api/[slug]/import/apply/route.ts new file mode 100644 index 0000000..8710092 --- /dev/null +++ b/src/app/api/[slug]/import/apply/route.ts @@ -0,0 +1,68 @@ +import { NextResponse } from 'next/server'; +import { prisma } from '@/lib/prisma'; +import { requireEditor } from '@/lib/guard'; +import type { ImportedSection } from '@/lib/import'; + +export const dynamic = 'force-dynamic'; + +// Applies a reviewed import to the DRAFT. mode 'replace' wipes the current draft +// first; mode 'add' appends after existing sections. AI-inferred data keeps its +// aiEstimated flags so the editor can badge it. +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 mode = body?.mode === 'replace' ? 'replace' : 'add'; + const sections: ImportedSection[] = Array.isArray(body?.sections) ? body.sections : []; + if (sections.length === 0) { + return NextResponse.json({ error: 'invalid' }, { status: 400 }); + } + + const restaurantId = guard.restaurant.id; + + await prisma.$transaction(async (tx) => { + if (mode === 'replace') { + await tx.product.deleteMany({ where: { restaurantId } }); + await tx.section.deleteMany({ where: { restaurantId } }); + } + + const startOrder = + mode === 'add' ? await tx.section.count({ where: { restaurantId } }) : 0; + + for (let si = 0; si < sections.length; si++) { + const s = sections[si]; + const section = await tx.section.create({ + data: { + restaurantId, + name: (s.name ?? {}) as object, + order: startOrder + si, + }, + }); + for (let pi = 0; pi < (s.products?.length ?? 0); pi++) { + const p = s.products[pi]; + const en = p.name?.en || p.description?.en; + await tx.product.create({ + data: { + sectionId: section.id, + restaurantId, + name: (p.name ?? {}) as object, + description: (p.description ?? {}) as object, + price: Number(p.price) || 0, + order: pi, + allergens: Array.isArray(p.allergens) ? p.allergens : [], + dietTags: Array.isArray(p.dietTags) ? p.dietTags : [], + macros: (p.macros ?? {}) as object, + media: [], + // Imported translations come from the model → mark English as auto. + translationStatus: (en ? { en: 'auto' } : {}) as object, + aiEstimated: (p.aiEstimated ?? {}) as object, + }, + }); + } + } + }); + + const count = sections.reduce((n, s) => n + (s.products?.length ?? 0), 0); + return NextResponse.json({ ok: true, sections: sections.length, products: count }); +} diff --git a/src/app/api/[slug]/import/route.ts b/src/app/api/[slug]/import/route.ts new file mode 100644 index 0000000..8950ba4 --- /dev/null +++ b/src/app/api/[slug]/import/route.ts @@ -0,0 +1,45 @@ +import { NextResponse } from 'next/server'; +import { requireEditor } from '@/lib/guard'; +import { resolveSource, extractMenu, type ImportMethod } from '@/lib/import'; +import type { Locale } from '@/i18n/config'; + +export const dynamic = 'force-dynamic'; +export const maxDuration = 120; + +// Extracts a menu from an uploaded file / link / pasted text using Claude and +// returns the structure for review. Does NOT touch 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 form = await req.formData().catch(() => null); + if (!form) return NextResponse.json({ error: 'invalid' }, { status: 400 }); + + const method = String(form.get('method') ?? '') as ImportMethod; + if (!['file', 'link', 'text'].includes(method)) { + return NextResponse.json({ error: 'invalid_method' }, { status: 400 }); + } + const fileEntry = form.get('file'); + + try { + const source = await resolveSource({ + method, + file: fileEntry instanceof File ? fileEntry : null, + link: String(form.get('link') ?? ''), + text: String(form.get('text') ?? ''), + }); + const result = await extractMenu(source, guard.restaurant.defaultLocale as Locale); + if (result.sections.length === 0) { + return NextResponse.json({ error: 'nothing_found' }, { status: 422 }); + } + return NextResponse.json(result); + } catch (err) { + const code = err instanceof Error ? err.message : 'import_failed'; + const known = ['empty_text', 'invalid_link', 'fetch_failed', 'no_file']; + console.error('import extract error', err); + return NextResponse.json( + { error: known.includes(code) ? code : 'import_failed' }, + { status: known.includes(code) ? 400 : 502 }, + ); + } +} diff --git a/src/app/api/[slug]/products/[id]/route.ts b/src/app/api/[slug]/products/[id]/route.ts index fad9b7c..571dede 100644 --- a/src/app/api/[slug]/products/[id]/route.ts +++ b/src/app/api/[slug]/products/[id]/route.ts @@ -12,6 +12,7 @@ const FIELDS = [ 'macros', 'media', 'translationStatus', + 'aiEstimated', 'sectionId', ] as const; diff --git a/src/app/api/[slug]/products/route.ts b/src/app/api/[slug]/products/route.ts index 88bd8d8..3dec3b5 100644 --- a/src/app/api/[slug]/products/route.ts +++ b/src/app/api/[slug]/products/route.ts @@ -30,6 +30,7 @@ export async function POST(req: Request, { params }: { params: { slug: string } macros: (body?.macros as object) ?? {}, media: (body?.media as object) ?? [], translationStatus: (body?.translationStatus as object) ?? {}, + aiEstimated: (body?.aiEstimated as object) ?? {}, }, }); return NextResponse.json(product); diff --git a/src/components/editor/CatalogTab.tsx b/src/components/editor/CatalogTab.tsx index 744ed52..4b2f25b 100644 --- a/src/components/editor/CatalogTab.tsx +++ b/src/components/editor/CatalogTab.tsx @@ -9,6 +9,7 @@ import { api } from './api'; import ProductEditor from './ProductEditor'; import SectionTitleEditor from './SectionTitleEditor'; import VersionHistory from './VersionHistory'; +import ImportModal from './ImportModal'; export default function CatalogTab({ slug, @@ -26,8 +27,10 @@ export default function CatalogTab({ onRestored: (name: string | null) => void; }) { const t = useTranslations('editor'); + const ti = useTranslations('import'); const locale = useLocale() as Locale; const [editing, setEditing] = useState<{ product: EditorProduct } | null>(null); + const [importOpen, setImportOpen] = useState(false); const [dragSection, setDragSection] = useState(null); const [dragProduct, setDragProduct] = useState<{ sectionId: string; id: string } | null>(null); @@ -55,6 +58,7 @@ export default function CatalogTab({ allergens: created.allergens ?? [], dietTags: created.dietTags ?? [], translationStatus: created.translationStatus ?? {}, + aiEstimated: created.aiEstimated ?? {}, }; setSections((prev) => prev.map((s) => (s.id === sectionId ? { ...s, products: [...s.products, product] } : s)), @@ -135,6 +139,12 @@ export default function CatalogTab({ > 👁 {t('viewMenu')} + + + + {step === 'input' && ( + <> + {/* Method selector */} +
+ {(['file', 'link', 'text'] as Method[]).map((m) => ( + + ))} +
+ + {method === 'file' && ( + + )} + {method === 'link' && ( + setLink(e.target.value)} + placeholder="https://…" + className="glass-soft rounded-2xl px-4 py-3 text-sm outline-none" + /> + )} + {method === 'text' && ( +