Relocate macros toggle and add per-section macros control

- Move the global 'Show macros' toggle from the Palette tab to the Catalog tab,
  next to 'Cargar menú', where catalog assembly lives
- Section.showMacros boolean (default true) + migration 0006; existing sections
  default to showing (so turning the global on shows all by default)
- Per-section toggle in the editor, visible only when the global toggle is on
- Hierarchy: global wins. A dish shows macros only if Restaurant.showMacros AND
  its Section.showMacros are both true. Applies to card flip, list tap-image, the
  gallery, and the color-code legend (legend shows only if some visible section does)
- Turning the global off only HIDES — macro data is never deleted; the disclaimer
  is reassuring ('Macros will stop showing to the public, but they are not deleted')
- Live read: global + per-section showMacros are overlaid onto the published
  snapshot at read time (new applyLiveSectionMacros helper) so toggles take effect
  instantly without republishing; old snapshots default section macros on
- sections PATCH accepts showMacros; settings PATCH still handles the global
- i18n: sectionMacros + soft disclaimer (es/en parity); hint reworded

Verified: build passes; 6 migrations apply; section toggle persists; /menu reflects
the global+section hierarchy live; macro data preserved in DB and API when toggled off.
This commit is contained in:
Jorem Juárez committed 2026-06-15 16:26:27 -06:00
1 parent 79cee9ebde
commit e4e8c50438
15 files changed
+140 -53

No files matched your search

+3 -1
View File
@@ -100,7 +100,9 @@
"copied": "Copied",
"paletteHint": "This does not affect the macro color code",
"showMacros": "Show macros on the menu",
"showMacrosHint": "When off, the public menu shows no macro layer at all."
"showMacrosHint": "Each section can hide its macros individually.",
"showMacrosDisclaimer": "Macros will stop showing to the public, but they are not deleted.",
"sectionMacros": "Macros in this section"
},
"qr": {
"templates": "Templates",
+3 -1
View File
@@ -100,7 +100,9 @@
"copied": "Copiado",
"paletteHint": "Esto no afecta el código de color de macros",
"showMacros": "Mostrar macros en el menú",
"showMacrosHint": "Si está apagado, el menú público no muestra ninguna capa de macros."
"showMacrosHint": "Cada sección puede ocultar sus macros individualmente.",
"showMacrosDisclaimer": "Las macros dejarán de mostrarse al público, pero no se borran.",
"sectionMacros": "Macros en esta sección"
},
"qr": {
"templates": "Plantillas",
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Section" ADD COLUMN "showMacros" BOOLEAN NOT NULL DEFAULT true;
+1
View File
@@ -55,6 +55,7 @@ model Section {
restaurantId String
name Json // { es, en }
order Int @default(0)
showMacros Boolean @default(true) // per-section override; only applies when Restaurant.showMacros is on
createdAt DateTime @default(now())
restaurant Restaurant @relation(fields: [restaurantId], references: [id], onDelete: Cascade)
+1
View File
@@ -46,6 +46,7 @@ export default async function EditorPage({
id: s.id,
name: s.name as { es?: string; en?: string },
order: s.order,
showMacros: s.showMacros,
products: s.products.map((p) => ({
id: p.id,
sectionId: p.sectionId,
+9 -3
View File
@@ -1,6 +1,7 @@
import { notFound } from 'next/navigation';
import { prisma } from '@/lib/prisma';
import { paletteToCssVars } from '@/lib/palette';
import { applyLiveSectionMacros } from '@/lib/menu';
import type { MenuSnapshot } from '@/lib/types';
import PublicMenu from '@/components/public/PublicMenu';
@@ -9,7 +10,10 @@ export const dynamic = 'force-dynamic';
async function getPublishedMenu(slug: string): Promise<MenuSnapshot | null> {
const restaurant = await prisma.restaurant.findUnique({
where: { slug },
include: { publishedVersion: true },
include: {
publishedVersion: true,
sections: { select: { id: true, showMacros: true } },
},
});
if (!restaurant || !restaurant.active) return null;
if (!restaurant.publishedVersion) {
@@ -27,9 +31,11 @@ async function getPublishedMenu(slug: string): Promise<MenuSnapshot | null> {
};
}
const snapshot = restaurant.publishedVersion.snapshot as unknown as MenuSnapshot;
// showMacros is read live (not from the snapshot) so toggling it takes effect
// immediately without republishing — and old snapshots without the flag default off.
// showMacros (global + per-section) is read live (not from the snapshot) so
// toggling takes effect immediately without republishing — old snapshots without
// the flags default to off (global) / on (section).
snapshot.restaurant.showMacros = restaurant.showMacros;
applyLiveSectionMacros(snapshot, restaurant.sections);
return snapshot;
}
+7 -2
View File
@@ -1,5 +1,6 @@
import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { applyLiveSectionMacros } from '@/lib/menu';
import type { MenuSnapshot } from '@/lib/types';
export const dynamic = 'force-dynamic';
@@ -8,7 +9,10 @@ export const dynamic = 'force-dynamic';
export async function GET(_req: Request, { params }: { params: { slug: string } }) {
const restaurant = await prisma.restaurant.findUnique({
where: { slug: params.slug },
include: { publishedVersion: true },
include: {
publishedVersion: true,
sections: { select: { id: true, showMacros: true } },
},
});
if (!restaurant || !restaurant.active) {
return NextResponse.json({ error: 'not_found' }, { status: 404 });
@@ -17,7 +21,8 @@ export async function GET(_req: Request, { params }: { params: { slug: string }
return NextResponse.json({ error: 'not_published' }, { status: 404 });
}
const snapshot = restaurant.publishedVersion.snapshot as unknown as MenuSnapshot;
// Read showMacros live so the toggle applies without republishing.
// Read showMacros (global + per-section) live so toggles apply without republishing.
snapshot.restaurant.showMacros = restaurant.showMacros;
applyLiveSectionMacros(snapshot, restaurant.sections);
return NextResponse.json(snapshot);
}
+2 -1
View File
@@ -10,8 +10,9 @@ export async function PATCH(
if ('error' in guard) return guard.error;
const body = await req.json().catch(() => null);
const data: { name?: object } = {};
const data: { name?: object; showMacros?: boolean } = {};
if (body?.name) data.name = body.name as object;
if (typeof body?.showMacros === 'boolean') data.showMacros = body.showMacros;
const result = await prisma.section.updateMany({
where: { id: params.id, restaurantId: guard.restaurant.id },
+71 -1
View File
@@ -16,6 +16,8 @@ export default function CatalogTab({
sections,
setSections,
ordersEnabled,
showMacros,
setShowMacros,
onPublish,
onRestored,
}: {
@@ -23,6 +25,8 @@ export default function CatalogTab({
sections: EditorSection[];
setSections: React.Dispatch<React.SetStateAction<EditorSection[]>>;
ordersEnabled: boolean;
showMacros: boolean;
setShowMacros: (v: boolean) => void;
onPublish: () => void;
onRestored: (name: string | null) => void;
}) {
@@ -31,13 +35,34 @@ export default function CatalogTab({
const locale = useLocale() as Locale;
const [editing, setEditing] = useState<{ product: EditorProduct } | null>(null);
const [importOpen, setImportOpen] = useState(false);
async function toggleGlobalMacros() {
const next = !showMacros;
setShowMacros(next);
await api(slug, '/settings', { method: 'PATCH', json: { showMacros: next } });
}
async function toggleSectionMacros(id: string) {
let next = true;
setSections((prev) =>
prev.map((s) => {
if (s.id !== id) return s;
next = !s.showMacros;
return { ...s, showMacros: next };
}),
);
await api(slug, `/sections/${id}`, { method: 'PATCH', json: { showMacros: next } });
}
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: [] }]);
setSections((prev) => [
...prev,
{ id: created.id, name, order: prev.length, showMacros: true, products: [] },
]);
}
async function deleteSection(id: string) {
@@ -153,6 +178,29 @@ export default function CatalogTab({
</button>
</div>
{/* Global macros toggle — lives here with catalog assembly (near Cargar menú) */}
<div className="glass flex items-center justify-between gap-3 rounded-3xl p-4">
<div className="min-w-0">
<div className="text-sm font-medium">{t('showMacros')}</div>
<div className="text-xs text-[var(--text)]/55">
{showMacros ? t('showMacrosHint') : t('showMacrosDisclaimer')}
</div>
</div>
<button
onClick={toggleGlobalMacros}
aria-pressed={showMacros}
className={`relative h-7 w-12 shrink-0 rounded-full transition ${
showMacros ? 'bg-green-500' : 'bg-gray-300'
}`}
>
<span
className={`absolute top-1 h-5 w-5 rounded-full bg-white transition-all ${
showMacros ? 'left-6' : 'left-1'
}`}
/>
</button>
</div>
{sections.map((s) => (
<section
key={s.id}
@@ -183,6 +231,28 @@ export default function CatalogTab({
</button>
</div>
{/* Per-section macros toggle — only when the global toggle is on */}
{showMacros && (
<button
onClick={() => toggleSectionMacros(s.id)}
aria-pressed={s.showMacros}
className="mb-3 flex w-full items-center justify-between gap-2 rounded-2xl bg-white/30 px-3 py-2 text-xs"
>
<span className="text-[var(--text)]/70">{t('sectionMacros')}</span>
<span
className={`relative h-5 w-9 shrink-0 rounded-full transition ${
s.showMacros ? 'bg-green-500' : 'bg-gray-300'
}`}
>
<span
className={`absolute top-0.5 h-4 w-4 rounded-full bg-white transition-all ${
s.showMacros ? 'left-[1.125rem]' : 'left-0.5'
}`}
/>
</span>
</button>
)}
<div className="flex flex-col gap-2">
{s.products.map((p) => (
<div
+4 -7
View File
@@ -17,6 +17,7 @@ export default function Editor({ data, baseUrl }: { data: EditorData; baseUrl: s
const [tab, setTab] = useState<Tab>('catalog');
const [sections, setSections] = useState<EditorSection[]>(data.sections);
const [ordersEnabled, setOrdersEnabled] = useState(data.ordersEnabled);
const [showMacros, setShowMacros] = useState(data.showMacros);
const [publishOpen, setPublishOpen] = useState(false);
const [publishedName, setPublishedName] = useState(data.publishedVersionName);
@@ -45,17 +46,13 @@ export default function Editor({ data, baseUrl }: { data: EditorData; baseUrl: s
sections={sections}
setSections={setSections}
ordersEnabled={ordersEnabled}
showMacros={showMacros}
setShowMacros={setShowMacros}
onPublish={() => setPublishOpen(true)}
onRestored={(name) => setPublishedName(name)}
/>
)}
{tab === 'palette' && (
<PaletteTab
slug={data.slug}
initialPalette={data.palette}
initialShowMacros={data.showMacros}
/>
)}
{tab === 'palette' && <PaletteTab slug={data.slug} initialPalette={data.palette} />}
{tab === 'orders' && (
<OrdersTab
slug={data.slug}
-30
View File
@@ -15,11 +15,9 @@ const FIELDS: { key: keyof Palette; label: string }[] = [
export default function PaletteTab({
slug,
initialPalette,
initialShowMacros,
}: {
slug: string;
initialPalette: Palette;
initialShowMacros: boolean;
}) {
const t = useTranslations('editor');
const tc = useTranslations('common');
@@ -27,16 +25,9 @@ export default function PaletteTab({
...PALETTE_PRESETS[0].palette,
...initialPalette,
});
const [showMacros, setShowMacros] = useState(initialShowMacros);
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState(false);
async function toggleMacros() {
const next = !showMacros;
setShowMacros(next);
await api(slug, '/settings', { method: 'PATCH', json: { showMacros: next } });
}
function update(next: Palette) {
setPalette(next);
setSaved(false);
@@ -111,27 +102,6 @@ export default function PaletteTab({
<p className="text-xs text-[var(--text)]/55">⚠️ {t('paletteHint')}</p>
{/* Show-macros toggle (controls whether the public menu exposes any macro layer) */}
<div className="glass flex items-center justify-between gap-3 rounded-3xl p-4">
<div className="min-w-0">
<div className="text-sm font-medium">{t('showMacros')}</div>
<div className="text-xs text-[var(--text)]/55">{t('showMacrosHint')}</div>
</div>
<button
onClick={toggleMacros}
aria-pressed={showMacros}
className={`relative h-7 w-12 shrink-0 rounded-full transition ${
showMacros ? 'bg-green-500' : 'bg-gray-300'
}`}
>
<span
className={`absolute top-1 h-5 w-5 rounded-full bg-white transition-all ${
showMacros ? 'left-6' : 'left-1'
}`}
/>
</button>
</div>
<button
onClick={save}
disabled={saving}
+1
View File
@@ -21,6 +21,7 @@ export type EditorSection = {
id: string;
name: { es?: string; en?: string };
order: number;
showMacros: boolean;
products: EditorProduct[];
};
+19 -7
View File
@@ -31,7 +31,9 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
);
const [activeSection, setActiveSection] = useState(sections[0]?.id ?? '');
const [gallery, setGallery] = useState<SnapshotProduct | null>(null);
const [gallery, setGallery] = useState<{ product: SnapshotProduct; showMacros: boolean } | null>(
null,
);
const [aiOpen, setAiOpen] = useState(false);
const [actionsOpen, setActionsOpen] = useState(false);
const [cart, setCart] = useState<CartLine[]>([]);
@@ -43,7 +45,11 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
const sectionRefs = useRef<Record<string, HTMLElement | null>>({});
const ordersEnabled = menu.restaurant.ordersEnabled;
const showMacros = menu.restaurant.showMacros;
// Macros hierarchy: global flag AND the section's own flag. The legend appears
// only if at least one visible section actually shows macros.
const globalMacros = menu.restaurant.showMacros;
const sectionShowsMacros = (s: { showMacros?: boolean }) => globalMacros && s.showMacros !== false;
const anyMacros = globalMacros && sections.some((s) => s.showMacros !== false);
function scrollToSection(id: string) {
setActiveSection(id);
@@ -93,7 +99,7 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
{/* View toggle (cards vs traditional list). Not persisted. */}
<div className="mb-4 flex items-center justify-end gap-3">
{showMacros && <div className="min-w-0 flex-1"><MacroLegend /></div>}
{anyMacros && <div className="min-w-0 flex-1"><MacroLegend /></div>}
<div className="glass-pill inline-flex shrink-0 rounded-full p-1 text-sm">
<button
onClick={() => setView('cards')}
@@ -132,7 +138,7 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
<ListRow
key={p.id}
product={p}
showMacros={showMacros}
showMacros={sectionShowsMacros(s)}
ordersEnabled={ordersEnabled}
onAdd={ordersEnabled ? addToCart : undefined}
/>
@@ -145,10 +151,12 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
key={p.id}
product={p}
index={i}
onOpenGallery={setGallery}
onOpenGallery={(prod) =>
setGallery({ product: prod, showMacros: sectionShowsMacros(s) })
}
onAdd={ordersEnabled ? addToCart : undefined}
ordersEnabled={ordersEnabled}
showMacros={showMacros}
showMacros={sectionShowsMacros(s)}
/>
))}
</div>
@@ -213,7 +221,11 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
{/* Modals */}
{gallery && (
<Gallery product={gallery} onClose={() => setGallery(null)} showMacros={showMacros} />
<Gallery
product={gallery.product}
onClose={() => setGallery(null)}
showMacros={gallery.showMacros}
/>
)}
{aiOpen && <AiConsultant slug={slug} onClose={() => setAiOpen(false)} />}
{orderOpen && (
+16
View File
@@ -39,6 +39,7 @@ export async function buildSnapshot(restaurantId: string): Promise<MenuSnapshot>
id: s.id,
name: s.name as LocalizedText,
order: s.order,
showMacros: s.showMacros,
products: s.products.map(
(p): SnapshotProduct => ({
id: p.id,
@@ -58,6 +59,20 @@ export async function buildSnapshot(restaurantId: string): Promise<MenuSnapshot>
};
}
// Overlay live per-section showMacros onto a published snapshot (matched by id)
// so section toggles take effect immediately without republishing. Sections not
// present live keep their snapshot value (default true).
export function applyLiveSectionMacros(
snapshot: MenuSnapshot,
liveSections: { id: string; showMacros: boolean }[],
): void {
const map = new Map(liveSections.map((s) => [s.id, s.showMacros]));
for (const sec of snapshot.sections) {
const live = map.get(sec.id);
sec.showMacros = live !== undefined ? live : (sec.showMacros ?? true);
}
}
// Create a published version from the current draft, keeping max 5 versions.
export async function publishVersion(
restaurantId: string,
@@ -111,6 +126,7 @@ export async function restoreSnapshotToDraft(
restaurantId,
name: s.name as object,
order: s.order,
showMacros: s.showMacros ?? true,
},
});
for (const p of s.products) {
+1
View File
@@ -44,6 +44,7 @@ export type SnapshotSection = {
id: string;
name: LocalizedText;
order: number;
showMacros: boolean;
products: SnapshotProduct[];
};