The per-section macros toggle read 'next' inside the setSections updater callback, which React runs during the render phase — after the synchronous PATCH had already fired. So 'next' stayed at its initial 'true', and turning a section OFF sent showMacros:true to the server: the DB never became false while the editor UI flipped, so the public kept showing that section's macros even though it looked off. Fix: compute 'next' from the current sections state before calling setSections, and PATCH that value. The public hierarchy (global AND section) and applyLiveSectionMacros were already correct. Verified: build passes; global ON + a section toggled OFF now persists showMacros=f in the DB and /menu returns that section showMacros:false, so its dishes hide macros.
351 lines
12 KiB
TypeScript
351 lines
12 KiB
TypeScript
'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';
|
|
import ImportModal from './ImportModal';
|
|
|
|
export default function CatalogTab({
|
|
slug,
|
|
sections,
|
|
setSections,
|
|
ordersEnabled,
|
|
showMacros,
|
|
setShowMacros,
|
|
onPublish,
|
|
onRestored,
|
|
}: {
|
|
slug: string;
|
|
sections: EditorSection[];
|
|
setSections: React.Dispatch<React.SetStateAction<EditorSection[]>>;
|
|
ordersEnabled: boolean;
|
|
showMacros: boolean;
|
|
setShowMacros: (v: boolean) => void;
|
|
onPublish: () => void;
|
|
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);
|
|
|
|
async function toggleGlobalMacros() {
|
|
const next = !showMacros;
|
|
setShowMacros(next);
|
|
await api(slug, '/settings', { method: 'PATCH', json: { showMacros: next } });
|
|
}
|
|
|
|
async function toggleSectionMacros(id: string) {
|
|
// Compute next from current state (NOT inside the setState updater — that runs
|
|
// during render, after this PATCH would already have read a stale value).
|
|
const section = sections.find((s) => s.id === id);
|
|
if (!section) return;
|
|
const next = !section.showMacros;
|
|
setSections((prev) => prev.map((s) => (s.id === id ? { ...s, showMacros: next } : s)));
|
|
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, showMacros: true, 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 ?? {},
|
|
aiEstimated: created.aiEstimated ?? {},
|
|
};
|
|
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={() => setImportOpen(true)}
|
|
className="glass-pill rounded-full px-4 py-2 text-sm font-medium"
|
|
>
|
|
✨ {ti('loadMenu')}
|
|
</button>
|
|
<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>
|
|
|
|
{/* 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}
|
|
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>
|
|
|
|
{/* 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
|
|
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}
|
|
/>
|
|
)}
|
|
|
|
{importOpen && (
|
|
<ImportModal
|
|
slug={slug}
|
|
onClose={() => setImportOpen(false)}
|
|
onApplied={() => {
|
|
// Reload to pull the freshly imported draft into the editor.
|
|
window.location.reload();
|
|
}}
|
|
/>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|