Add AI smart menu import (Cargar menú)
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.
This commit is contained in:
1 parent
24a412f793
commit
112e95dc28
19 files changed
+819
-16
No files matched your search
@@ -57,6 +57,7 @@ export default async function EditorPage({
|
||||
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' },
|
||||
aiEstimated: p.aiEstimated as { macros?: boolean; allergens?: boolean },
|
||||
})),
|
||||
})),
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -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 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ const FIELDS = [
|
||||
'macros',
|
||||
'media',
|
||||
'translationStatus',
|
||||
'aiEstimated',
|
||||
'sectionId',
|
||||
] as const;
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user