From 9a40a988e0e1064f10dc57d22be73c192a88bd0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorem=20Ju=C3=A1rez?= Date: Sun, 14 Jun 2026 02:00:45 -0600 Subject: [PATCH] Add artistic QR (templates + customization) with qr-code-styling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Editor QR tab now generates a styled, scannable QR with live preview and clean PNG/SVG export (no frame or text — the owner lays it out). - Restaurant.qrConfig JSON persists the styling (migration 0003) - qr-code-styling (MIT) runs client-side in QrTab: preview + WYSIWYG PNG (2048px) and vector SVG export, avoiding native canvas deps in the alpine image - Controls: dots color/gradient, background (incl. transparent), corners color, dot & corner shapes, optional center logo (uploaded via /upload, capped at 20%) - Scannability: error correction forced to 'H' whenever there's a logo or color; WCAG contrast check warns on low contrast; persistent 'verify before printing' notice - Templates inherit the menu palette but every value is independently editable - QR always targets {APP_BASE_URL}/{slug} - PATCH /api/[slug]/qr saves config; GET stays as a config-aware server fallback - i18n (es/en) for the qr namespace; glassmorphism, mobile-first Verified: build passes; migration 0003 applies; PATCH persists qrConfig; GET honors saved colors/ECC (png + colored svg); auth guard returns 401. --- messages/en.json | 30 ++ messages/es.json | 30 ++ package-lock.json | 19 + package.json | 5 +- .../0003_restaurant_qr_config/migration.sql | 2 + prisma/schema.prisma | 1 + src/app/[slug]/editor/page.tsx | 3 +- src/app/api/[slug]/qr/route.ts | 51 +- src/components/editor/Editor.tsx | 9 +- src/components/editor/QrTab.tsx | 436 ++++++++++++++++-- src/components/editor/types.ts | 13 + src/lib/contrast.ts | 40 ++ 12 files changed, 594 insertions(+), 45 deletions(-) create mode 100644 prisma/migrations/0003_restaurant_qr_config/migration.sql create mode 100644 src/lib/contrast.ts diff --git a/messages/en.json b/messages/en.json index 87ebd49..902279b 100644 --- a/messages/en.json +++ b/messages/en.json @@ -87,6 +87,36 @@ "copied": "Copied", "paletteHint": "This does not affect the macro color code" }, + "qr": { + "templates": "Templates", + "customize": "Customize", + "dotsColor": "Dots color", + "cornersColor": "Corners color", + "background": "Background", + "transparent": "Transparent", + "dotShape": "Dot shape", + "cornerShape": "Corner shape", + "gradient": "Gradient", + "logo": "Center logo", + "uploadLogo": "Upload logo", + "logoHint": "The logo takes up at most 20% of the code so it doesn't hurt scanning.", + "errorLevel": "Error correction", + "lowContrast": "Contrast between dots and background is low; the QR may not scan well. Use higher-contrast colors.", + "verifyScan": "Check that your QR scans well before printing.", + "shapes": { + "square": "Square", + "rounded": "Rounded", + "dots": "Dots", + "classy": "Classy", + "classy-rounded": "Classy rounded", + "extra-rounded": "Extra rounded" + }, + "corners": { + "square": "Square", + "dot": "Dot", + "extra-rounded": "Rounded" + } + }, "import": { "title": "Load menu", "loadMenu": "Load menu", diff --git a/messages/es.json b/messages/es.json index a7a9fbc..bc167f9 100644 --- a/messages/es.json +++ b/messages/es.json @@ -87,6 +87,36 @@ "copied": "Copiado", "paletteHint": "Esto no afecta el código de color de macros" }, + "qr": { + "templates": "Plantillas", + "customize": "Personalizar", + "dotsColor": "Color de puntos", + "cornersColor": "Color de esquinas", + "background": "Fondo", + "transparent": "Transparente", + "dotShape": "Forma de puntos", + "cornerShape": "Forma de esquinas", + "gradient": "Degradado", + "logo": "Logo al centro", + "uploadLogo": "Subir logo", + "logoHint": "El logo ocupa máximo 20% del código para no afectar el escaneo.", + "errorLevel": "Corrección de errores", + "lowContrast": "El contraste entre puntos y fondo es bajo; el QR podría no escanear bien. Usa colores con más contraste.", + "verifyScan": "Verifica que tu QR escanea bien antes de imprimir.", + "shapes": { + "square": "Cuadrado", + "rounded": "Redondeado", + "dots": "Puntos", + "classy": "Elegante", + "classy-rounded": "Elegante redondeado", + "extra-rounded": "Muy redondeado" + }, + "corners": { + "square": "Cuadrada", + "dot": "Punto", + "extra-rounded": "Redondeada" + } + }, "import": { "title": "Cargar menú", "loadMenu": "Cargar menú", diff --git a/package-lock.json b/package-lock.json index 734ab10..11c1dc7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,6 +15,7 @@ "jose": "^5.9.6", "next": "14.2.21", "next-intl": "^3.26.3", + "qr-code-styling": "^1.9.2", "qrcode": "^1.5.4", "react": "^18.3.1", "react-dom": "^18.3.1", @@ -2233,6 +2234,18 @@ "fsevents": "2.3.3" } }, + "node_modules/qr-code-styling": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/qr-code-styling/-/qr-code-styling-1.9.2.tgz", + "integrity": "sha512-RgJaZJ1/RrXJ6N0j7a+pdw3zMBmzZU4VN2dtAZf8ZggCfRB5stEQ3IoDNGaNhYY3nnZKYlYSLl5YkfWN5dPutg==", + "license": "MIT", + "dependencies": { + "qrcode-generator": "^1.4.4" + }, + "engines": { + "node": ">=18.18.0" + } + }, "node_modules/qrcode": { "version": "1.5.4", "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", @@ -2250,6 +2263,12 @@ "node": ">=10.13.0" } }, + "node_modules/qrcode-generator": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/qrcode-generator/-/qrcode-generator-1.5.2.tgz", + "integrity": "sha512-pItrW0Z9HnDBnFmgiNrY1uxRdri32Uh9EjNYLPVC2zZ3ZRIIEqBoDgm4DkvDwNNDHTK7FNkmr8zAa77BYc9xNw==", + "license": "MIT" + }, "node_modules/queue-microtask": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", diff --git a/package.json b/package.json index 143a5d2..94c2e82 100644 --- a/package.json +++ b/package.json @@ -23,10 +23,11 @@ "jose": "^5.9.6", "next": "14.2.21", "next-intl": "^3.26.3", + "qr-code-styling": "^1.9.2", "qrcode": "^1.5.4", - "xlsx": "^0.18.5", "react": "^18.3.1", - "react-dom": "^18.3.1" + "react-dom": "^18.3.1", + "xlsx": "^0.18.5" }, "devDependencies": { "@types/bcryptjs": "^2.4.6", diff --git a/prisma/migrations/0003_restaurant_qr_config/migration.sql b/prisma/migrations/0003_restaurant_qr_config/migration.sql new file mode 100644 index 0000000..9f9c4c4 --- /dev/null +++ b/prisma/migrations/0003_restaurant_qr_config/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "Restaurant" ADD COLUMN "qrConfig" JSONB NOT NULL DEFAULT '{}'; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 65932e7..dba2ca8 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -18,6 +18,7 @@ model Restaurant { username String hashedPassword String palette Json @default("{}") + qrConfig Json @default("{}") // artistic QR styling (qr-code-styling config) ordersEnabled Boolean @default(false) defaultLocale String @default("es") active Boolean @default(true) diff --git a/src/app/[slug]/editor/page.tsx b/src/app/[slug]/editor/page.tsx index c9fbdbf..9c8faa1 100644 --- a/src/app/[slug]/editor/page.tsx +++ b/src/app/[slug]/editor/page.tsx @@ -2,7 +2,7 @@ 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 { EditorData, QrConfig } from '@/components/editor/types'; import type { Palette } from '@/lib/types'; import Editor from '@/components/editor/Editor'; @@ -39,6 +39,7 @@ export default async function EditorPage({ ordersEnabled: restaurant.ordersEnabled, defaultLocale: restaurant.defaultLocale as 'es' | 'en', palette: (restaurant.palette as Palette) ?? {}, + qrConfig: (restaurant.qrConfig as QrConfig) ?? {}, publishedVersionName: restaurant.publishedVersion?.versionName ?? null, sections: restaurant.sections.map((s) => ({ id: s.id, diff --git a/src/app/api/[slug]/qr/route.ts b/src/app/api/[slug]/qr/route.ts index a4c2ed4..09d7556 100644 --- a/src/app/api/[slug]/qr/route.ts +++ b/src/app/api/[slug]/qr/route.ts @@ -1,28 +1,39 @@ import { NextResponse } from 'next/server'; import QRCode from 'qrcode'; import { prisma } from '@/lib/prisma'; +import { requireEditor } from '@/lib/guard'; export const dynamic = 'force-dynamic'; -// Generates the public-menu QR as PNG or SVG. +type QrConfig = { + dotsColor?: string; + background?: string; // hex or 'transparent' + errorCorrectionLevel?: 'L' | 'M' | 'Q' | 'H'; +}; + +// GET: server-side fallback QR (honors saved colors + ECC). The editor's +// artistic export (shapes/gradients/logo) is generated client-side with +// qr-code-styling; this endpoint stays available for direct/basic use. export async function GET(req: Request, { params }: { params: { slug: string } }) { const restaurant = await prisma.restaurant.findUnique({ where: { slug: params.slug }, - select: { id: true }, + select: { id: true, qrConfig: true }, }); if (!restaurant) return NextResponse.json({ error: 'not_found' }, { status: 404 }); + const cfg = (restaurant.qrConfig as QrConfig) ?? {}; + const dark = cfg.dotsColor || '#2a2520'; + // QR libs can't render a transparent module color; fall back to white bg here. + const light = cfg.background && cfg.background !== 'transparent' ? cfg.background : '#ffffff'; + const ecc = cfg.errorCorrectionLevel || 'H'; + 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}`; + const opts = { margin: 2, width: 1024, errorCorrectionLevel: ecc, color: { dark, light } } as const; if (format === 'svg') { - const svg = await QRCode.toString(url, { - type: 'svg', - margin: 2, - width: 1024, - color: { dark: '#2a2520', light: '#ffffff' }, - }); + const svg = await QRCode.toString(url, { type: 'svg', ...opts }); return new NextResponse(svg, { headers: { 'Content-Type': 'image/svg+xml', @@ -31,12 +42,7 @@ export async function GET(req: Request, { params }: { params: { slug: string } } }); } - const buffer = await QRCode.toBuffer(url, { - type: 'png', - margin: 2, - width: 1024, - color: { dark: '#2a2520', light: '#ffffff' }, - }); + const buffer = await QRCode.toBuffer(url, { type: 'png', ...opts }); return new NextResponse(new Uint8Array(buffer), { headers: { 'Content-Type': 'image/png', @@ -44,3 +50,20 @@ export async function GET(req: Request, { params }: { params: { slug: string } } }, }); } + +// PATCH: persist the artistic QR config (qrConfig JSON) on the restaurant. +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 config = body?.qrConfig; + if (!config || typeof config !== 'object') { + return NextResponse.json({ error: 'invalid' }, { status: 400 }); + } + await prisma.restaurant.update({ + where: { id: guard.restaurant.id }, + data: { qrConfig: config as object }, + }); + return NextResponse.json({ ok: true }); +} diff --git a/src/components/editor/Editor.tsx b/src/components/editor/Editor.tsx index 6960154..83a8d51 100644 --- a/src/components/editor/Editor.tsx +++ b/src/components/editor/Editor.tsx @@ -57,7 +57,14 @@ export default function Editor({ data, baseUrl }: { data: EditorData; baseUrl: s setOrdersEnabled={setOrdersEnabled} /> )} - {tab === 'qr' && } + {tab === 'qr' && ( + + )} {/* Bottom tab bar */}