pestana descargas y subcategorias funcionando
This commit is contained in:
@@ -688,12 +688,12 @@ select {
|
||||
}
|
||||
|
||||
/* ════════════════════════════════
|
||||
CATEGORÍAS
|
||||
ESTILOS DE CATEGORÍAS (vista admin)
|
||||
════════════════════════════════ */
|
||||
.categorias-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
|
||||
gap: 16px;
|
||||
grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.categoria-card {
|
||||
@@ -1030,6 +1030,273 @@ select {
|
||||
color: #b45309;
|
||||
}
|
||||
|
||||
/* ════════════════════════════════
|
||||
ÁRBOL DE SUBCATEGORÍAS (dentro de la card de categoría)
|
||||
Opción A: cards 2-col, acciones hover-reveal, menú kebab
|
||||
════════════════════════════════ */
|
||||
.categoria-card {
|
||||
padding: 0;
|
||||
overflow: visible; /* allow kebab menus to escape the card */
|
||||
display: block; /* override inherited flex-column from base rule */
|
||||
text-align: left; /* override inherited text-align: center */
|
||||
align-items: stretch; /* override inherited align-items: center */
|
||||
z-index: 1; /* hover card stays above siblings */
|
||||
}
|
||||
.categoria-card.menu-host { z-index: 50; } /* card with open menu */
|
||||
|
||||
.categoria-header {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr auto auto;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
padding: 16px 18px;
|
||||
}
|
||||
|
||||
.categoria-header .categoria-icon { font-size: 1.9rem; line-height: 1; }
|
||||
.categoria-header .categoria-meta { min-width: 0; }
|
||||
.categoria-header .categoria-nombre {
|
||||
font-weight: 700;
|
||||
font-size: 1.02rem;
|
||||
color: var(--ink);
|
||||
line-height: 1.2;
|
||||
}
|
||||
.categoria-header .categoria-id {
|
||||
font-size: 0.72rem;
|
||||
color: var(--ink-mute);
|
||||
font-family: ui-monospace, SFMono-Regular, monospace;
|
||||
margin-top: 3px;
|
||||
}
|
||||
.categoria-header .categoria-count {
|
||||
font-size: 0.78rem;
|
||||
color: var(--ink-mute);
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Acciones de categoría: solo contienen el ⋯ (todo lo demás está dentro del menú) */
|
||||
.categoria-actions {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.subcat-tree {
|
||||
border-top: 1px solid var(--line);
|
||||
background: rgba(255, 255, 255, 0.35);
|
||||
padding: 4px 0;
|
||||
border-bottom-left-radius: calc(var(--radius-md) - 1.5px);
|
||||
border-bottom-right-radius: calc(var(--radius-md) - 1.5px);
|
||||
}
|
||||
|
||||
.subcat-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 8px 18px 8px 44px;
|
||||
position: relative;
|
||||
font-size: 0.88rem;
|
||||
transition: background .15s ease;
|
||||
}
|
||||
.subcat-row:hover { background: rgba(255,255,255,0.55); }
|
||||
.subcat-row::before {
|
||||
content: '└';
|
||||
position: absolute;
|
||||
left: 28px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
color: var(--ink-mute);
|
||||
font-size: 0.78rem;
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.subcat-children .subcat-row { padding-left: 72px; }
|
||||
.subcat-children .subcat-row::before { left: 56px; }
|
||||
|
||||
.subcat-info { display: flex; align-items: baseline; gap: 8px; min-width: 0; }
|
||||
.subcat-name {
|
||||
font-weight: 600;
|
||||
color: var(--ink);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.subcat-id {
|
||||
font-size: 0.7rem;
|
||||
color: var(--ink-mute);
|
||||
font-family: ui-monospace, SFMono-Regular, monospace;
|
||||
opacity: 0.75;
|
||||
}
|
||||
|
||||
/* Acciones de subcat: solo contienen el ⋯ */
|
||||
.subcat-actions {
|
||||
display: flex;
|
||||
gap: 2px;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.btn-icon-tiny {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
font-size: 0.85rem;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
border: 1px solid transparent;
|
||||
color: var(--ink-mute);
|
||||
cursor: pointer;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: all .15s ease;
|
||||
font-weight: 600;
|
||||
}
|
||||
.btn-icon-tiny:hover {
|
||||
background: rgba(255,255,255,0.85);
|
||||
border-color: var(--line);
|
||||
color: var(--ink);
|
||||
}
|
||||
.btn-icon-tiny.btn-icon-danger:hover {
|
||||
background: rgba(239, 68, 68, 0.12);
|
||||
border-color: rgba(239, 68, 68, 0.3);
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
/* ════════════════════════════════
|
||||
MENÚ KEBAB (drop-down ⋯)
|
||||
════════════════════════════════ */
|
||||
.menu-dropdown {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.menu-panel:not([hidden]) {
|
||||
position: absolute;
|
||||
top: calc(100% + 6px);
|
||||
right: 0;
|
||||
min-width: 190px;
|
||||
background: var(--white);
|
||||
border: 1.5px solid var(--line-strong);
|
||||
border-radius: var(--radius-md);
|
||||
box-shadow: var(--shadow-md);
|
||||
padding: 5px;
|
||||
z-index: 100;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
animation: menuFadeIn .14s ease;
|
||||
transform-origin: top right;
|
||||
}
|
||||
|
||||
@keyframes menuFadeIn {
|
||||
from { opacity: 0; transform: translateY(-4px) scale(0.97); }
|
||||
to { opacity: 1; transform: translateY(0) scale(1); }
|
||||
}
|
||||
|
||||
.menu-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 8px 10px;
|
||||
background: transparent;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
color: var(--ink);
|
||||
font: inherit;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
width: 100%;
|
||||
transition: background .12s ease, color .12s ease;
|
||||
}
|
||||
.menu-item:hover {
|
||||
background: rgba(167, 139, 250, 0.12);
|
||||
color: var(--violet-deep);
|
||||
}
|
||||
.menu-item-danger { color: var(--danger); }
|
||||
.menu-item-danger:hover {
|
||||
background: rgba(239, 68, 68, 0.10);
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.menu-icon {
|
||||
font-size: 0.95rem;
|
||||
line-height: 1;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 18px;
|
||||
}
|
||||
|
||||
.menu-header {
|
||||
padding: 7px 10px 8px;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 700;
|
||||
color: var(--ink);
|
||||
border-bottom: 1px solid var(--line);
|
||||
margin: 0 0 4px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
/* Breadcrumb dentro del modal de subcategoría */
|
||||
.subcat-breadcrumb {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 10px 12px;
|
||||
background: rgba(167, 139, 250, 0.08);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.subcat-breadcrumb .bc-cat {
|
||||
color: var(--ink);
|
||||
font-weight: 600;
|
||||
}
|
||||
.subcat-breadcrumb .bc-arrow { color: var(--ink-mute); }
|
||||
.subcat-breadcrumb .bc-new {
|
||||
color: var(--violet);
|
||||
font-weight: 600;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
/* Upload: grupos de subcategoría + indicador de destino */
|
||||
.subcat-group { animation: subcatFadeIn .2s ease; }
|
||||
@keyframes subcatFadeIn {
|
||||
from { opacity: 0; transform: translateY(-4px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.upload-destino {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 14px;
|
||||
background: rgba(124, 92, 252, 0.08);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
font-size: 0.88rem;
|
||||
}
|
||||
.upload-destino-label {
|
||||
color: var(--ink-mute);
|
||||
font-weight: 600;
|
||||
font-size: 0.78rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
.upload-destino-path {
|
||||
color: var(--ink);
|
||||
font-weight: 600;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.you-badge {
|
||||
display: inline-block;
|
||||
margin-left: 6px;
|
||||
@@ -1294,6 +1561,17 @@ select {
|
||||
.subtab { padding: 8px 12px; font-size: 0.82rem; }
|
||||
.subtab-placeholder { padding: 32px 16px; }
|
||||
.subtab-placeholder-icon { font-size: 2.6rem; }
|
||||
.categoria-header {
|
||||
grid-template-columns: auto 1fr;
|
||||
grid-template-rows: auto auto;
|
||||
gap: 8px 12px;
|
||||
}
|
||||
.categoria-header .categoria-count { grid-column: 1; }
|
||||
.categoria-header .categoria-actions { grid-column: 1 / -1; }
|
||||
.subcat-row { padding-left: 32px; }
|
||||
.subcat-row::before { left: 18px; }
|
||||
.subcat-children .subcat-row { padding-left: 52px; }
|
||||
.subcat-children .subcat-row::before { left: 38px; }
|
||||
}
|
||||
|
||||
/* ════════════════════════════════
|
||||
|
||||
@@ -766,19 +766,39 @@ function renderCategorias(categorias, productos) {
|
||||
grid.innerHTML = categorias.map(c => {
|
||||
const count = countByCat[c.id] || 0;
|
||||
const isSistema = c.id === 'sin-categoria';
|
||||
const subcats = Array.isArray(c.subcategorias) ? c.subcategorias : [];
|
||||
const tieneSubcats = subcats.length > 0;
|
||||
|
||||
return `
|
||||
<div class="categoria-card ${isSistema ? 'categoria-sistema' : ''}">
|
||||
${isSistema ? '<span class="categoria-sistema-badge">Sistema</span>' : ''}
|
||||
<div class="categoria-icon">${c.icono || '📦'}</div>
|
||||
<div class="categoria-nombre">${escapeHtml(c.nombre)}</div>
|
||||
<div class="categoria-id">${escapeHtml(c.id)}</div>
|
||||
<div class="categoria-count">${count} item${count === 1 ? '' : 's'}</div>
|
||||
${!isSistema ? `
|
||||
<div class="categoria-actions">
|
||||
<button class="btn-icon" onclick="abrirEditarCategoria('${escapeAttr(c.id)}')" title="Editar" type="button">✏️</button>
|
||||
<button class="btn-icon btn-icon-danger" onclick="abrirEliminarCategoria('${escapeAttr(c.id)}','${escapeAttr(c.nombre)}')" title="Eliminar" type="button">🗑️</button>
|
||||
<div class="categoria-header">
|
||||
<div class="categoria-icon">${c.icono || '📦'}</div>
|
||||
<div class="categoria-meta">
|
||||
<div class="categoria-nombre">${escapeHtml(c.nombre)}</div>
|
||||
<div class="categoria-id">${escapeHtml(c.id)}</div>
|
||||
</div>
|
||||
` : ''}
|
||||
<div class="categoria-count">${count} item${count === 1 ? '' : 's'}</div>
|
||||
${!isSistema ? `
|
||||
<div class="categoria-actions">
|
||||
<div class="menu-dropdown">
|
||||
<button class="btn-icon-tiny menu-toggle" type="button" aria-label="Más acciones" aria-haspopup="true" aria-expanded="false">⋯</button>
|
||||
<div class="menu-panel" hidden>
|
||||
<div class="menu-header" title="${escapeAttr(c.nombre)}">${escapeHtml(c.nombre)}</div>
|
||||
<button type="button" class="menu-item" data-action="add-sub-cat" data-id="${escapeAttr(c.id)}">
|
||||
<span class="menu-icon">+</span> Agregar subcategoría
|
||||
</button>
|
||||
<button type="button" class="menu-item" data-action="edit-cat" data-id="${escapeAttr(c.id)}">
|
||||
<span class="menu-icon">✏️</span> Editar nombre e icono
|
||||
</button>
|
||||
<button type="button" class="menu-item menu-item-danger" data-action="delete-cat" data-id="${escapeAttr(c.id)}" data-name="${escapeAttr(c.nombre)}">
|
||||
<span class="menu-icon">🗑️</span> Eliminar categoría
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
${tieneSubcats ? `<div class="subcat-tree">${renderSubcatRows(subcats, [c.id])}</div>` : ''}
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
@@ -937,6 +957,319 @@ function setupCategoriasModals() {
|
||||
document.getElementById('btnCrearCategoria').addEventListener('click', abrirCrearCategoria);
|
||||
document.getElementById('formCategoria').addEventListener('submit', guardarCategoria);
|
||||
document.getElementById('btnConfirmarEliminarCategoria').addEventListener('click', confirmarEliminarCategoria);
|
||||
document.getElementById('formSubcategoria').addEventListener('submit', guardarSubcategoria);
|
||||
document.getElementById('btnConfirmarEliminarSubcat').addEventListener('click', confirmarEliminarSubcategoria);
|
||||
setupKebabMenus();
|
||||
}
|
||||
|
||||
// ════════════════════════════════
|
||||
// MENÚ KEBAB (drop-down ⋯) — para categoría y subcats
|
||||
// - Click en .menu-toggle → abre/cierra
|
||||
// - Click en .menu-item → ejecuta acción, cierra
|
||||
// - Click fuera / Escape → cierra todos
|
||||
// - Al abrir, marca .menu-active en el contenedor para que no se oculte al perder hover
|
||||
// ════════════════════════════════
|
||||
function setupKebabMenus() {
|
||||
document.addEventListener('click', e => {
|
||||
// Click en el toggle ⋯
|
||||
const toggle = e.target.closest('.menu-toggle');
|
||||
if (toggle) {
|
||||
e.stopPropagation();
|
||||
const dropdown = toggle.parentElement;
|
||||
const panel = dropdown.querySelector('.menu-panel');
|
||||
if (!panel) return;
|
||||
const wasOpen = !panel.hidden;
|
||||
closeAllKebabMenus();
|
||||
if (!wasOpen) {
|
||||
panel.hidden = false;
|
||||
toggle.setAttribute('aria-expanded', 'true');
|
||||
// Marcar la card como host para que flote sobre los vecinos
|
||||
const card = dropdown.closest('.categoria-card');
|
||||
if (card) card.classList.add('menu-host');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Click en un item del menú
|
||||
const item = e.target.closest('.menu-item');
|
||||
if (item) {
|
||||
const action = item.dataset.action;
|
||||
closeAllKebabMenus();
|
||||
if (action === 'add-sub-cat') abrirCrearSubcategoria(item.dataset.id);
|
||||
else if (action === 'add-sub-sub-cat') abrirCrearSubcatHijo(item.dataset.cat, item.dataset.sub);
|
||||
else if (action === 'edit-subcat') abrirEditarSubcategoria(item.dataset.cat, item.dataset.sub);
|
||||
else if (action === 'delete-subcat') abrirEliminarSubcategoria(item.dataset.cat, item.dataset.sub, item.dataset.name);
|
||||
else if (action === 'edit-cat') abrirEditarCategoria(item.dataset.id);
|
||||
else if (action === 'delete-cat') abrirEliminarCategoria(item.dataset.id, item.dataset.name);
|
||||
return;
|
||||
}
|
||||
|
||||
// Click fuera de cualquier dropdown
|
||||
if (!e.target.closest('.menu-dropdown')) {
|
||||
closeAllKebabMenus();
|
||||
}
|
||||
});
|
||||
|
||||
// Escape cierra todos
|
||||
document.addEventListener('keydown', e => {
|
||||
if (e.key === 'Escape') closeAllKebabMenus();
|
||||
});
|
||||
}
|
||||
|
||||
function closeAllKebabMenus() {
|
||||
document.querySelectorAll('.menu-panel').forEach(p => p.hidden = true);
|
||||
document.querySelectorAll('.menu-toggle').forEach(b => b.setAttribute('aria-expanded', 'false'));
|
||||
document.querySelectorAll('.categoria-card.menu-host')
|
||||
.forEach(c => c.classList.remove('menu-host'));
|
||||
}
|
||||
|
||||
// ════════════════════════════════
|
||||
// SUBCATEGORÍAS (CRUD sobre el árbol anidado)
|
||||
// Estado: editingSubcat = { parentId, subId } cuando se está editando
|
||||
// deletingSubcat = { parentId, subId, nombre } cuando se va a eliminar
|
||||
// ════════════════════════════════
|
||||
let editingSubcat = null;
|
||||
let deletingSubcat = null;
|
||||
|
||||
// Render recursivo de subcategorías como filas anidadas dentro de la card de la categoría
|
||||
function renderSubcatRows(subcats, parentPath) {
|
||||
if (!Array.isArray(subcats) || subcats.length === 0) return '';
|
||||
// parentPath = [c.id] → render nivel 2 (subs). El + aparece (pueden tener sub-subs).
|
||||
// parentPath = [c.id, s.id] → render nivel 3 (sub-subs). El + NO aparece (límite 3 niveles).
|
||||
const puedenTenerHijos = parentPath.length === 1;
|
||||
return subcats.map(s => {
|
||||
const path = [...parentPath, s.id];
|
||||
const tieneSubSub = Array.isArray(s.subcategorias) && s.subcategorias.length > 0;
|
||||
return `
|
||||
<div class="subcat-row" data-subcat-id="${escapeAttr(s.id)}">
|
||||
<div class="subcat-info">
|
||||
<span class="subcat-name">${escapeHtml(s.nombre)}</span>
|
||||
<span class="subcat-id">${escapeHtml(s.id)}</span>
|
||||
</div>
|
||||
<div class="subcat-actions">
|
||||
<div class="menu-dropdown">
|
||||
<button class="btn-icon-tiny menu-toggle" type="button" aria-label="Más acciones" aria-haspopup="true" aria-expanded="false">⋯</button>
|
||||
<div class="menu-panel" hidden>
|
||||
<div class="menu-header" title="${escapeAttr(s.nombre)}">${escapeHtml(s.nombre)}</div>
|
||||
${puedenTenerHijos ? `<button type="button" class="menu-item" data-action="add-sub-sub-cat" data-cat="${escapeAttr(parentPath[0])}" data-sub="${escapeAttr(s.id)}">
|
||||
<span class="menu-icon">+</span> Agregar sub-subcategoría
|
||||
</button>` : ''}
|
||||
<button type="button" class="menu-item" data-action="edit-subcat" data-cat="${escapeAttr(parentPath[0])}" data-sub="${escapeAttr(s.id)}">
|
||||
<span class="menu-icon">✏️</span> Editar nombre
|
||||
</button>
|
||||
<button type="button" class="menu-item menu-item-danger" data-action="delete-subcat" data-cat="${escapeAttr(parentPath[0])}" data-sub="${escapeAttr(s.id)}" data-name="${escapeAttr(s.nombre)}">
|
||||
<span class="menu-icon">🗑️</span> Eliminar subcategoría
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
${tieneSubSub ? `<div class="subcat-children">${renderSubcatRows(s.subcategorias, path)}</div>` : ''}
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
async function abrirCrearSubcategoria(parentId) {
|
||||
editingSubcat = null;
|
||||
document.getElementById('modalSubcategoriaTitulo').textContent = 'Crear subcategoría';
|
||||
document.getElementById('btnGuardarSubcategoria').textContent = 'Crear';
|
||||
document.getElementById('subcatNombre').value = '';
|
||||
document.getElementById('subcatIdHint').textContent = '';
|
||||
document.getElementById('subcategoriaError').classList.remove('show');
|
||||
document.getElementById('subcategoriaError').textContent = '';
|
||||
// Mostrar breadcrumb del padre (solo la categoría)
|
||||
const categorias = await fetch('/api/categorias', { credentials: 'include' }).then(r => r.json());
|
||||
const parent = categorias.find(c => c.id === parentId);
|
||||
if (parent) {
|
||||
document.getElementById('subcatBreadcrumb').innerHTML =
|
||||
`<span class="bc-cat">${parent.icono || '📦'} ${escapeHtml(parent.nombre)}</span><span class="bc-arrow">›</span><span class="bc-new">Nueva subcategoría</span>`;
|
||||
}
|
||||
abrirModal('modalSubcategoria');
|
||||
|
||||
document.getElementById('subcatNombre').oninput = e => {
|
||||
const slug = slugifyLocal(e.target.value);
|
||||
document.getElementById('subcatIdHint').textContent = slug ? `ID: ${slug}` : '';
|
||||
};
|
||||
|
||||
// Guardar el parentId en el dataset del form para usarlo al enviar
|
||||
document.getElementById('formSubcategoria').dataset.parentId = parentId;
|
||||
document.getElementById('formSubcategoria').dataset.subId = '';
|
||||
}
|
||||
|
||||
async function abrirCrearSubcatHijo(parentCatId, parentSubId) {
|
||||
// Para crear una sub-subcategoría, el "padre" es la subcategoría (no la categoría raíz)
|
||||
editingSubcat = null;
|
||||
document.getElementById('modalSubcategoriaTitulo').textContent = 'Crear sub-subcategoría';
|
||||
document.getElementById('btnGuardarSubcategoria').textContent = 'Crear';
|
||||
document.getElementById('subcatNombre').value = '';
|
||||
document.getElementById('subcatIdHint').textContent = '';
|
||||
document.getElementById('subcategoriaError').classList.remove('show');
|
||||
document.getElementById('subcategoriaError').textContent = '';
|
||||
|
||||
const categorias = await fetch('/api/categorias', { credentials: 'include' }).then(r => r.json());
|
||||
const path = getCategoryPathCliente(categorias, parentSubId);
|
||||
if (path) {
|
||||
const crumbs = path.map(n => `<span class="bc-cat">${n.icono || '📦'} ${escapeHtml(n.nombre)}</span><span class="bc-arrow">›</span>`).join('');
|
||||
document.getElementById('subcatBreadcrumb').innerHTML = crumbs + '<span class="bc-new">Nueva sub-subcategoría</span>';
|
||||
}
|
||||
abrirModal('modalSubcategoria');
|
||||
|
||||
document.getElementById('subcatNombre').oninput = e => {
|
||||
const slug = slugifyLocal(e.target.value);
|
||||
document.getElementById('subcatIdHint').textContent = slug ? `ID: ${slug}` : '';
|
||||
};
|
||||
|
||||
document.getElementById('formSubcategoria').dataset.parentId = parentCatId;
|
||||
document.getElementById('formSubcategoria').dataset.subId = parentSubId;
|
||||
}
|
||||
|
||||
async function abrirEditarSubcategoria(parentCatId, subId) {
|
||||
const categorias = await fetch('/api/categorias', { credentials: 'include' }).then(r => r.json());
|
||||
const sub = findSubcatCliente(categorias, subId);
|
||||
if (!sub) return;
|
||||
|
||||
editingSubcat = { parentCatId, subId };
|
||||
document.getElementById('modalSubcategoriaTitulo').textContent = 'Editar subcategoría';
|
||||
document.getElementById('btnGuardarSubcategoria').textContent = 'Guardar cambios';
|
||||
document.getElementById('subcatNombre').value = sub.nombre;
|
||||
document.getElementById('subcatIdHint').textContent = `ID: ${sub.id} (no se puede cambiar)`;
|
||||
document.getElementById('subcategoriaError').classList.remove('show');
|
||||
document.getElementById('subcategoriaError').textContent = '';
|
||||
|
||||
const path = getCategoryPathCliente(categorias, subId);
|
||||
if (path) {
|
||||
const crumbs = path.slice(0, -1).map(n => `<span class="bc-cat">${n.icono || '📦'} ${escapeHtml(n.nombre)}</span><span class="bc-arrow">›</span>`).join('');
|
||||
document.getElementById('subcatBreadcrumb').innerHTML = crumbs + `<span class="bc-cat">${escapeHtml(sub.nombre)}</span>`;
|
||||
}
|
||||
abrirModal('modalSubcategoria');
|
||||
|
||||
document.getElementById('formSubcategoria').dataset.parentId = parentCatId;
|
||||
document.getElementById('formSubcategoria').dataset.subId = subId;
|
||||
}
|
||||
|
||||
function abrirEliminarSubcategoria(parentCatId, subId, nombre) {
|
||||
deletingSubcat = { parentCatId, subId, nombre };
|
||||
document.getElementById('eliminarSubcatNombre').textContent = nombre;
|
||||
document.getElementById('eliminarSubcatError').classList.remove('show');
|
||||
document.getElementById('eliminarSubcatError').textContent = '';
|
||||
abrirModal('modalEliminarSubcategoria');
|
||||
}
|
||||
|
||||
// Helpers cliente (espejo de los del backend)
|
||||
function getCategoryPathCliente(categorias, id, trail = []) {
|
||||
for (const c of categorias) {
|
||||
const next = [...trail, c];
|
||||
if (c.id === id) return next;
|
||||
if (Array.isArray(c.subcategorias) && c.subcategorias.length) {
|
||||
const found = getCategoryPathCliente(c.subcategorias, id, next);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function findSubcatCliente(categorias, id) {
|
||||
for (const c of categorias) {
|
||||
if (Array.isArray(c.subcategorias)) {
|
||||
const found = findInSubcatsCliente(c.subcategorias, id);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function findInSubcatsCliente(subcats, id) {
|
||||
for (const s of subcats) {
|
||||
if (s.id === id) return s;
|
||||
if (Array.isArray(s.subcategorias) && s.subcategorias.length) {
|
||||
const found = findInSubcatsCliente(s.subcategorias, id);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function guardarSubcategoria(e) {
|
||||
e.preventDefault();
|
||||
const nombre = document.getElementById('subcatNombre').value.trim();
|
||||
const errEl = document.getElementById('subcategoriaError');
|
||||
const btn = document.getElementById('btnGuardarSubcategoria');
|
||||
const form = document.getElementById('formSubcategoria');
|
||||
const parentId = form.dataset.parentId;
|
||||
const subId = form.dataset.subId;
|
||||
|
||||
if (!nombre) return;
|
||||
|
||||
btn.disabled = true;
|
||||
btn.textContent = editingSubcat ? 'Guardando…' : 'Creando…';
|
||||
|
||||
try {
|
||||
let url, method, body;
|
||||
|
||||
if (editingSubcat) {
|
||||
// EDITAR: PUT /api/categorias/:parentId/subcategorias/:subId
|
||||
url = `/api/categorias/${encodeURIComponent(parentId)}/subcategorias/${encodeURIComponent(subId)}`;
|
||||
method = 'PUT';
|
||||
body = { nombre };
|
||||
} else if (subId) {
|
||||
// CREAR sub-subcat: POST con parentSubId en el body
|
||||
url = `/api/categorias/${encodeURIComponent(parentId)}/subcategorias`;
|
||||
method = 'POST';
|
||||
body = { nombre, parentSubId: subId };
|
||||
} else {
|
||||
// CREAR subcat nivel 1: POST simple
|
||||
url = `/api/categorias/${encodeURIComponent(parentId)}/subcategorias`;
|
||||
method = 'POST';
|
||||
body = { nombre };
|
||||
}
|
||||
|
||||
const res = await fetch(url, {
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || 'Error al guardar');
|
||||
|
||||
editingSubcat = null;
|
||||
cerrarModal('modalSubcategoria');
|
||||
await cargarCategorias();
|
||||
cargarEstadisticas();
|
||||
} catch (err) {
|
||||
errEl.textContent = err.message;
|
||||
errEl.classList.add('show');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = editingSubcat ? 'Guardar cambios' : 'Crear';
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmarEliminarSubcategoria() {
|
||||
if (!deletingSubcat) return;
|
||||
|
||||
const btn = document.getElementById('btnConfirmarEliminarSubcat');
|
||||
const errEl = document.getElementById('eliminarSubcatError');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Eliminando…';
|
||||
|
||||
try {
|
||||
const res = await fetch(
|
||||
`/api/categorias/${encodeURIComponent(deletingSubcat.parentCatId)}/subcategorias/${encodeURIComponent(deletingSubcat.subId)}`,
|
||||
{ method: 'DELETE', credentials: 'include' }
|
||||
);
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || 'Error al eliminar');
|
||||
|
||||
deletingSubcat = null;
|
||||
cerrarModal('modalEliminarSubcategoria');
|
||||
await cargarCategorias();
|
||||
cargarEstadisticas();
|
||||
} catch (err) {
|
||||
errEl.textContent = err.message;
|
||||
errEl.classList.add('show');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'Sí, eliminar';
|
||||
}
|
||||
}
|
||||
|
||||
// ════════════════════════════════
|
||||
@@ -971,6 +1304,9 @@ async function cargarCategoriasEnUpload() {
|
||||
const categorias = await res.json();
|
||||
if (!Array.isArray(categorias)) throw new Error('Respuesta no es array');
|
||||
|
||||
// Cachear el árbol completo (con subcategorías) en el módulo para la cascada
|
||||
uploadCategoriasTree = categorias;
|
||||
|
||||
const seleccionPrevia = select.value;
|
||||
select.innerHTML = '<option value="">— Selecciona una categoría —</option>';
|
||||
categorias
|
||||
@@ -982,22 +1318,138 @@ async function cargarCategoriasEnUpload() {
|
||||
select.appendChild(opt);
|
||||
});
|
||||
if (seleccionPrevia) select.value = seleccionPrevia;
|
||||
|
||||
console.log(`[upload] Categorías cargadas: ${categorias.filter(c => c.id !== SIN_CAT_ID).length}`);
|
||||
} catch (err) {
|
||||
console.error('[upload] Error cargando categorías:', err);
|
||||
// Fallback visible para el usuario
|
||||
const error = document.getElementById('uploadError');
|
||||
if (error) error.textContent = 'No se pudieron cargar las categorías. Recarga la página.';
|
||||
}
|
||||
}
|
||||
|
||||
// Árbol completo cacheado para la cascada del upload
|
||||
let uploadCategoriasTree = [];
|
||||
|
||||
// Se ejecuta cuando el usuario cambia la categoría
|
||||
function onCategoriaChange() {
|
||||
const catId = document.getElementById('uploadCategoria').value;
|
||||
const subGrp = document.getElementById('uploadSubcatGroup');
|
||||
const subSel = document.getElementById('uploadSubcategoria');
|
||||
const subSubGrp = document.getElementById('uploadSubSubcatGroup');
|
||||
const subSubSel = document.getElementById('uploadSubSubcategoria');
|
||||
|
||||
// Reset
|
||||
subSel.innerHTML = '<option value="">— Selecciona una subcategoría —</option>';
|
||||
subSubSel.innerHTML = '<option value="">— Selecciona una sub-subcategoría —</option>';
|
||||
subGrp.style.display = 'none';
|
||||
subSubGrp.style.display = 'none';
|
||||
|
||||
if (!catId) {
|
||||
actualizarBreadcrumbDestino();
|
||||
updateSubmitButton();
|
||||
return;
|
||||
}
|
||||
|
||||
const cat = uploadCategoriasTree.find(c => c.id === catId);
|
||||
if (!cat) return;
|
||||
|
||||
if (Array.isArray(cat.subcategorias) && cat.subcategorias.length > 0) {
|
||||
subGrp.style.display = '';
|
||||
cat.subcategorias.forEach(s => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = s.id;
|
||||
opt.textContent = `${s.icono || '📂'} ${s.nombre}`;
|
||||
subSel.appendChild(opt);
|
||||
});
|
||||
}
|
||||
actualizarBreadcrumbDestino();
|
||||
updateSubmitButton();
|
||||
}
|
||||
|
||||
// Se ejecuta cuando el usuario cambia la subcategoría
|
||||
function onSubcategoriaChange() {
|
||||
const catId = document.getElementById('uploadCategoria').value;
|
||||
const subId = document.getElementById('uploadSubcategoria').value;
|
||||
const subSubGrp = document.getElementById('uploadSubSubcatGroup');
|
||||
const subSubSel = document.getElementById('uploadSubSubcategoria');
|
||||
|
||||
subSubSel.innerHTML = '<option value="">— Selecciona una sub-subcategoría —</option>';
|
||||
subSubGrp.style.display = 'none';
|
||||
|
||||
if (!catId || !subId) {
|
||||
actualizarBreadcrumbDestino();
|
||||
updateSubmitButton();
|
||||
return;
|
||||
}
|
||||
|
||||
const cat = uploadCategoriasTree.find(c => c.id === catId);
|
||||
if (!cat || !Array.isArray(cat.subcategorias)) return;
|
||||
|
||||
const sub = cat.subcategorias.find(s => s.id === subId);
|
||||
if (!sub) return;
|
||||
|
||||
if (Array.isArray(sub.subcategorias) && sub.subcategorias.length > 0) {
|
||||
subSubGrp.style.display = '';
|
||||
sub.subcategorias.forEach(ss => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = ss.id;
|
||||
opt.textContent = `${ss.icono || '📂'} ${ss.nombre}`;
|
||||
subSubSel.appendChild(opt);
|
||||
});
|
||||
}
|
||||
actualizarBreadcrumbDestino();
|
||||
updateSubmitButton();
|
||||
}
|
||||
|
||||
// Muestra el breadcrumb del destino actual (cat > sub1 > sub2)
|
||||
function actualizarBreadcrumbDestino() {
|
||||
const cont = document.getElementById('uploadDestino');
|
||||
const path = document.getElementById('uploadDestinoPath');
|
||||
if (!cont || !path) return;
|
||||
|
||||
const catId = document.getElementById('uploadCategoria').value;
|
||||
const subId = document.getElementById('uploadSubcategoria').value;
|
||||
const subSubId= document.getElementById('uploadSubSubcategoria').value;
|
||||
|
||||
if (!catId) { cont.style.display = 'none'; return; }
|
||||
|
||||
const cat = uploadCategoriasTree.find(c => c.id === catId);
|
||||
if (!cat) { cont.style.display = 'none'; return; }
|
||||
|
||||
const parts = [`${cat.icono || '📦'} ${cat.nombre}`];
|
||||
if (subId) {
|
||||
const sub = (cat.subcategorias || []).find(s => s.id === subId);
|
||||
if (sub) {
|
||||
parts.push(`${sub.icono || '📂'} ${sub.nombre}`);
|
||||
if (subSubId) {
|
||||
const subSub = (sub.subcategorias || []).find(s => s.id === subSubId);
|
||||
if (subSub) parts.push(`${subSub.icono || '📂'} ${subSub.nombre}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
path.textContent = parts.join(' › ');
|
||||
cont.style.display = '';
|
||||
}
|
||||
|
||||
// Devuelve el array `sub` que se enviará al backend (la cadena hasta la hoja)
|
||||
function getSubPathActual() {
|
||||
const catId = document.getElementById('uploadCategoria').value;
|
||||
const subId = document.getElementById('uploadSubcategoria').value;
|
||||
const subSubId = document.getElementById('uploadSubSubcategoria').value;
|
||||
|
||||
if (!catId) return [];
|
||||
const path = [];
|
||||
if (subId) path.push(subId);
|
||||
if (subSubId) path.push(subSubId);
|
||||
return path;
|
||||
}
|
||||
|
||||
function setupProductosUpload() {
|
||||
const dropzone = document.getElementById('dropzone');
|
||||
const inputFotos = document.getElementById('inputFotos');
|
||||
const btnLimpiar = document.getElementById('btnLimpiarPreview');
|
||||
const form = document.getElementById('formUploadProductos');
|
||||
const select = document.getElementById('uploadCategoria');
|
||||
const selectSub = document.getElementById('uploadSubcategoria');
|
||||
const selectSubSub= document.getElementById('uploadSubSubcategoria');
|
||||
|
||||
if (!dropzone || !inputFotos) return;
|
||||
|
||||
@@ -1034,7 +1486,10 @@ function setupProductosUpload() {
|
||||
renderPreview();
|
||||
});
|
||||
|
||||
select.addEventListener('change', updateSubmitButton);
|
||||
// Cascada: categoría → subcategoría → sub-subcategoría
|
||||
select.addEventListener('change', onCategoriaChange);
|
||||
if (selectSub) selectSub.addEventListener('change', onSubcategoriaChange);
|
||||
if (selectSubSub) selectSubSub.addEventListener('change', updateSubmitButton);
|
||||
|
||||
form.addEventListener('submit', submitUpload);
|
||||
}
|
||||
@@ -1126,10 +1581,27 @@ function renderPreview() {
|
||||
|
||||
function updateSubmitButton() {
|
||||
const btn = document.getElementById('btnSubirProductos');
|
||||
const select = document.getElementById('uploadCategoria');
|
||||
const catId = document.getElementById('uploadCategoria').value;
|
||||
const validos = pendingFiles.filter(p => p.isValid).length;
|
||||
const hayCat = !!select.value;
|
||||
btn.disabled = !(hayCat && validos > 0);
|
||||
if (!catId || validos === 0) {
|
||||
btn.disabled = true;
|
||||
return;
|
||||
}
|
||||
// Validar que la cadena llegue a una hoja
|
||||
const cat = uploadCategoriasTree.find(c => c.id === catId);
|
||||
if (!cat) { btn.disabled = true; return; }
|
||||
const catTieneSubcats = Array.isArray(cat.subcategorias) && cat.subcategorias.length > 0;
|
||||
if (catTieneSubcats) {
|
||||
const subId = document.getElementById('uploadSubcategoria').value;
|
||||
if (!subId) { btn.disabled = true; return; }
|
||||
const sub = cat.subcategorias.find(s => s.id === subId);
|
||||
if (!sub) { btn.disabled = true; return; }
|
||||
if (Array.isArray(sub.subcategorias) && sub.subcategorias.length > 0) {
|
||||
const subSubId = document.getElementById('uploadSubSubcategoria').value;
|
||||
if (!subSubId) { btn.disabled = true; return; }
|
||||
}
|
||||
}
|
||||
btn.disabled = false;
|
||||
}
|
||||
|
||||
async function submitUpload(e) {
|
||||
@@ -1158,8 +1630,11 @@ async function submitUpload(e) {
|
||||
btn.querySelector('.btn-text').textContent = 'Subiendo…';
|
||||
btn.querySelector('.btn-spinner').style.display = 'inline-block';
|
||||
|
||||
const subPath = getSubPathActual();
|
||||
|
||||
const fd = new FormData();
|
||||
fd.append('categoria', select.value);
|
||||
fd.append('sub', JSON.stringify(subPath));
|
||||
validos.forEach(item => fd.append('fotos', item.file, item.file.name));
|
||||
|
||||
try {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=DM+Serif+Display:ital@0;1&family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
|
||||
<link rel="stylesheet" href="admin.css?v=6">
|
||||
<link rel="stylesheet" href="admin.css?v=16">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -133,6 +133,22 @@
|
||||
<span class="form-hint">Todas las fotos subidas se guardarán en esta carpeta.</span>
|
||||
</div>
|
||||
|
||||
<div class="form-group subcat-group" id="uploadSubcatGroup" style="display:none">
|
||||
<label for="uploadSubcategoria">Subcategoría</label>
|
||||
<select id="uploadSubcategoria">
|
||||
<option value="">— Selecciona una subcategoría —</option>
|
||||
</select>
|
||||
<span class="form-hint">Esta categoría tiene subcategorías. Elige la hoja donde van los productos.</span>
|
||||
</div>
|
||||
|
||||
<div class="form-group subcat-group" id="uploadSubSubcatGroup" style="display:none">
|
||||
<label for="uploadSubSubcategoria">Sub-subcategoría</label>
|
||||
<select id="uploadSubSubcategoria">
|
||||
<option value="">— Selecciona una sub-subcategoría —</option>
|
||||
</select>
|
||||
<span class="form-hint">Esta subcategoría tiene sub-subcategorías. Elige la hoja final.</span>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label>Zona de subida</label>
|
||||
<div class="dropzone" id="dropzone">
|
||||
@@ -155,6 +171,11 @@
|
||||
<div class="upload-preview-grid" id="previewGrid"></div>
|
||||
</div>
|
||||
|
||||
<div class="upload-destino" id="uploadDestino" style="display:none">
|
||||
<span class="upload-destino-label">Destino:</span>
|
||||
<span class="upload-destino-path" id="uploadDestinoPath"></span>
|
||||
</div>
|
||||
|
||||
<div class="upload-summary" id="uploadSummary" style="display:none"></div>
|
||||
|
||||
<div class="form-error" id="uploadError" role="alert"></div>
|
||||
@@ -498,6 +519,61 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- MODAL: Crear/Editar subcategoría -->
|
||||
<div class="modal" id="modalSubcategoria" style="display:none">
|
||||
<div class="modal-backdrop" data-close-modal="modalSubcategoria"></div>
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h3 id="modalSubcategoriaTitulo">Crear subcategoría</h3>
|
||||
<button class="modal-close" data-close-modal="modalSubcategoria" type="button" aria-label="Cerrar">✕</button>
|
||||
</div>
|
||||
<form id="formSubcategoria" class="modal-form">
|
||||
<div class="form-group">
|
||||
<label for="subcatNombre">Nombre</label>
|
||||
<input type="text" id="subcatNombre" required maxlength="40" autocomplete="off">
|
||||
<span class="form-hint" id="subcatIdHint"></span>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Padre</label>
|
||||
<div class="subcat-breadcrumb" id="subcatBreadcrumb"></div>
|
||||
<span class="form-hint">La subcategoría heredará el icono de la categoría padre.</span>
|
||||
</div>
|
||||
<div class="form-error" id="subcategoriaError" role="alert"></div>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn btn-ghost" data-close-modal="modalSubcategoria">Cancelar</button>
|
||||
<button type="submit" class="btn btn-primary" id="btnGuardarSubcategoria">Crear</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- MODAL: Confirmar eliminar subcategoría -->
|
||||
<div class="modal modal-sm" id="modalEliminarSubcategoria" style="display:none">
|
||||
<div class="modal-backdrop" data-close-modal="modalEliminarSubcategoria"></div>
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h3>¿Eliminar subcategoría?</h3>
|
||||
<button class="modal-close" data-close-modal="modalEliminarSubcategoria" type="button" aria-label="Cerrar">✕</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p>Vas a eliminar la subcategoría <strong id="eliminarSubcatNombre"></strong>.</p>
|
||||
<div class="alert-warning">
|
||||
<span>📁</span>
|
||||
<div>
|
||||
<strong>Los productos asignados a esta subcategoría pasarán a la categoría padre.</strong>
|
||||
<p>(Aún no hay productos con subcategoría — este efecto se aplicará cuando se implemente la carga de productos por subcategoría.)</p>
|
||||
</div>
|
||||
</div>
|
||||
<p class="modal-warning">Esta acción no se puede deshacer.</p>
|
||||
<div class="form-error" id="eliminarSubcatError" role="alert"></div>
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn btn-ghost" data-close-modal="modalEliminarSubcategoria">Cancelar</button>
|
||||
<button type="button" class="btn btn-danger" id="btnConfirmarEliminarSubcat">Sí, eliminar</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- MODAL: Confirmar eliminar categoría -->
|
||||
<div class="modal modal-sm" id="modalEliminarCategoria" style="display:none">
|
||||
<div class="modal-backdrop" data-close-modal="modalEliminarCategoria"></div>
|
||||
@@ -545,6 +621,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="admin.js?v=6"></script>
|
||||
<script src="admin.js?v=16"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+149
-22
@@ -18,6 +18,7 @@ function escapeHtml(str) {
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
let catActiva = 'todos';
|
||||
let subActiva = []; // [nivel0, nivel1, ...] — null = "Todos" en ese nivel
|
||||
let busqueda = '';
|
||||
let cargando = true;
|
||||
|
||||
@@ -56,29 +57,151 @@ async function cargarDatos() {
|
||||
}
|
||||
|
||||
// ════════════════════════════════
|
||||
// RENDER CATEGORÍAS
|
||||
// HELPERS DE FILTRADO POR SUBRAMA
|
||||
// ════════════════════════════════
|
||||
// RENDER TAGS FILTROS
|
||||
// ════════════════════════════════
|
||||
function renderTags() {
|
||||
const cont = document.getElementById('filtrosTags');
|
||||
// Filtrar la categoría del sistema "sin-categoria" de los tags
|
||||
const visibles = categorias.filter(c => c.id !== 'sin-categoria');
|
||||
cont.innerHTML =
|
||||
`<button class="tag active" data-cat="todos">Todos</button>` +
|
||||
visibles.map(cat => `<button class="tag" data-cat="${cat.id}"><span class="tag-icon">${cat.icono || '📦'}</span> ${cat.nombre}</button>`).join('');
|
||||
|
||||
cont.querySelectorAll('.tag').forEach(tag => {
|
||||
tag.addEventListener('click', () => {
|
||||
catActiva = tag.dataset.cat;
|
||||
cont.querySelectorAll('.tag').forEach(t => t.classList.remove('active'));
|
||||
tag.classList.add('active');
|
||||
renderProductos();
|
||||
});
|
||||
// Devuelve los productos que matchean la rama actual (cat + sub[niveles anteriores])
|
||||
// y cuyo sub[i] === id. Sirve para contar/mostrar subcats con productos.
|
||||
function productosEnNivel(catId, nivelesPrevios, idNivel) {
|
||||
return productos.filter(p => {
|
||||
if (!p || p.cat !== catId) return false;
|
||||
if (p.img && p.img.startsWith('agotados/')) return false;
|
||||
// El sub del producto debe tener al menos la longitud de nivelesPrevios + 1
|
||||
const sub = Array.isArray(p.sub) ? p.sub : [];
|
||||
if (sub.length < nivelesPrevios.length + 1) return false;
|
||||
// Coincidir con los niveles previos
|
||||
for (let i = 0; i < nivelesPrevios.length; i++) {
|
||||
if (sub[i] !== nivelesPrevios[i]) return false;
|
||||
}
|
||||
// El nivel actual debe ser este id
|
||||
return sub[nivelesPrevios.length] === idNivel;
|
||||
});
|
||||
}
|
||||
|
||||
// Devuelve el nodo del árbol (categoría o subcat) según el path
|
||||
function getNodo(catId, niveles) {
|
||||
const cat = categorias.find(c => c.id === catId);
|
||||
if (!cat) return null;
|
||||
let nodo = cat;
|
||||
for (const id of niveles) {
|
||||
if (!Array.isArray(nodo.subcategorias)) return null;
|
||||
const sig = nodo.subcategorias.find(s => s.id === id);
|
||||
if (!sig) return null;
|
||||
nodo = sig;
|
||||
}
|
||||
return nodo;
|
||||
}
|
||||
|
||||
// ════════════════════════════════
|
||||
// RENDER TAGS FILTROS (multinivel)
|
||||
// ════════════════════════════════
|
||||
function renderTags() {
|
||||
const cont = document.getElementById('filtrosTags');
|
||||
cont.innerHTML = '';
|
||||
|
||||
// ——— Nivel 0: Categorías ———
|
||||
const catsVisibles = categorias.filter(c => c.id !== 'sin-categoria');
|
||||
const nivel0 = document.createElement('div');
|
||||
nivel0.className = 'filtros-tags filtros-nivel';
|
||||
nivel0.innerHTML =
|
||||
`<button class="tag ${catActiva === 'todos' ? 'active' : ''}" data-nivel="0" data-id="todos">Todos</button>` +
|
||||
catsVisibles.map(cat => {
|
||||
const tieneSubcats = Array.isArray(cat.subcategorias) && cat.subcategorias.length > 0;
|
||||
// Solo mostrar la categoría como tag si tiene productos directos O tiene subcats con productos
|
||||
if (tieneSubcats) {
|
||||
// No renderizar la categoría como "hoja" — sus subcats la cubren
|
||||
// PERO si alguna subcat es hoja con productos, sí tiene sentido mostrarla igual
|
||||
// porque al hacer click se entra al nivel 1
|
||||
}
|
||||
return `<button class="tag ${catActiva === cat.id ? 'active' : ''}" data-nivel="0" data-id="${cat.id}">
|
||||
<span class="tag-icon">${cat.icono || '📦'}</span> ${cat.nombre}
|
||||
</button>`;
|
||||
}).join('');
|
||||
cont.appendChild(nivel0);
|
||||
|
||||
// ——— Niveles 1+ : subcategorías (solo si catActiva está elegida) ———
|
||||
if (catActiva !== 'todos') {
|
||||
const cat = categorias.find(c => c.id === catActiva);
|
||||
if (cat && Array.isArray(cat.subcategorias) && cat.subcategorias.length > 0) {
|
||||
renderNivelSub(cont, cat, [], 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Wire click handlers
|
||||
cont.querySelectorAll('.tag').forEach(tag => {
|
||||
tag.addEventListener('click', () => onTagClick(parseInt(tag.dataset.nivel, 10), tag.dataset.id));
|
||||
});
|
||||
}
|
||||
|
||||
// Renderiza un nivel de subcategorías. `previos` = niveles ya elegidos arriba.
|
||||
function renderNivelSub(cont, nodo, previos, nivel) {
|
||||
if (!Array.isArray(nodo.subcategorias) || nodo.subcategorias.length === 0) return;
|
||||
|
||||
// Subcats que tienen productos en este nivel o cuyas sub-subs tienen productos
|
||||
const subsVisibles = nodo.subcategorias.filter(s => {
|
||||
const tieneSubSub = Array.isArray(s.subcategorias) && s.subcategorias.length > 0;
|
||||
if (tieneSubSub) {
|
||||
// Esta subcat NO recibe productos directamente. Mostrar solo si ALGUNA
|
||||
// de sus sub-subs tiene productos.
|
||||
return s.subcategorias.some(ss =>
|
||||
productosEnNivel(catActiva, [...previos, s.id], ss.id).length > 0
|
||||
);
|
||||
} else {
|
||||
// Hoja: recibe productos. Mostrar si tiene al menos uno.
|
||||
return productosEnNivel(catActiva, [...previos], s.id).length > 0;
|
||||
}
|
||||
});
|
||||
|
||||
if (subsVisibles.length === 0) return;
|
||||
|
||||
const nivelEl = document.createElement('div');
|
||||
nivelEl.className = 'filtros-tags filtros-nivel';
|
||||
const idTodos = `__all_${nivel}`;
|
||||
nivelEl.innerHTML =
|
||||
`<span class="filtros-nivel-label">${escapeHtml(nodo.nombre || '')}</span>` +
|
||||
`<button class="tag ${subActiva[nivel - 1] == null ? 'active' : ''}" data-nivel="${nivel}" data-id="${idTodos}">Todos</button>` +
|
||||
subsVisibles.map(s => {
|
||||
const esActivo = subActiva[nivel - 1] === s.id;
|
||||
return `<button class="tag ${esActivo ? 'active' : ''}" data-nivel="${nivel}" data-id="${s.id}">
|
||||
<span class="tag-icon">${s.icono || '📂'}</span> ${escapeHtml(s.nombre)}
|
||||
</button>`;
|
||||
}).join('');
|
||||
cont.appendChild(nivelEl);
|
||||
|
||||
// Si la subcat activa tiene sub-subs, renderizar el siguiente nivel
|
||||
if (subActiva[nivel - 1]) {
|
||||
const subActivaNodo = nodo.subcategorias.find(s => s.id === subActiva[nivel - 1]);
|
||||
if (subActivaNodo && Array.isArray(subActivaNodo.subcategorias) && subActivaNodo.subcategorias.length > 0) {
|
||||
renderNivelSub(cont, subActivaNodo, [...previos, subActiva[nivel - 1]], nivel + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function onTagClick(nivel, id) {
|
||||
if (nivel === 0) {
|
||||
if (id === 'todos') {
|
||||
catActiva = 'todos';
|
||||
} else {
|
||||
catActiva = id;
|
||||
}
|
||||
subActiva = []; // reset sub al cambiar categoría
|
||||
} else {
|
||||
if (id.startsWith('__all_')) {
|
||||
subActiva[nivel - 1] = null;
|
||||
} else {
|
||||
subActiva[nivel - 1] = id;
|
||||
}
|
||||
// Resetear niveles más profundos
|
||||
subActiva = subActiva.slice(0, nivel);
|
||||
// Rellenar con null hasta el nivel actual
|
||||
while (subActiva.length < nivel) subActiva.push(null);
|
||||
}
|
||||
renderTags();
|
||||
renderProductos();
|
||||
}
|
||||
|
||||
function sincronizarTag(cat) {
|
||||
// Legacy — mantenido por compatibilidad, pero ya no se usa
|
||||
document.querySelectorAll('.tag').forEach(t => {
|
||||
t.classList.toggle('active', t.dataset.cat === cat);
|
||||
});
|
||||
@@ -92,8 +215,6 @@ function renderProductos() {
|
||||
const empty = document.getElementById('emptyState');
|
||||
const contador = document.getElementById('contador');
|
||||
|
||||
// Filtrar productos sin categoría (sin-categoria) y productos AGOTADOS
|
||||
// (imagen movida a la carpeta "agotados/") — no se muestran en el catálogo público.
|
||||
let filtrados = productos.filter(p =>
|
||||
p.cat &&
|
||||
p.cat !== 'sin-categoria' &&
|
||||
@@ -101,7 +222,15 @@ function renderProductos() {
|
||||
);
|
||||
|
||||
if (catActiva !== 'todos') {
|
||||
filtrados = filtrados.filter(p => p.cat === catActiva);
|
||||
filtrados = filtrados.filter(p => {
|
||||
if (p.cat !== catActiva) return false;
|
||||
// Validar que la cadena de sub coincida
|
||||
const sub = Array.isArray(p.sub) ? p.sub : [];
|
||||
for (let i = 0; i < subActiva.length; i++) {
|
||||
if (subActiva[i] != null && sub[i] !== subActiva[i]) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
if (busqueda.trim()) {
|
||||
@@ -128,13 +257,11 @@ function renderProductos() {
|
||||
|
||||
grid.innerHTML = filtrados.map((p, i) => {
|
||||
const cat = categorias.find(c => c.id === p.cat);
|
||||
// Fallbacks: si no hay nombre, usar la referencia; si no hay descripción, ocultar
|
||||
const nombre = p.nombre || p.ref || 'Sin nombre';
|
||||
const desc = p.desc || '';
|
||||
const precio = (p.precio !== undefined && p.precio !== null && p.precio !== '')
|
||||
? `$${Number(p.precio).toLocaleString('es-CO')}`
|
||||
: '—';
|
||||
// La ruta en el JSON es relativa a /Imagenes/ (ej: "bolsos/AF100.webp")
|
||||
const imgSrc = p.img && p.img.startsWith('/') ? p.img : `/Imagenes/${p.img}`;
|
||||
return `
|
||||
<article class="producto-card" style="animation-delay: ${i * 0.04}s">
|
||||
|
||||
@@ -484,6 +484,28 @@ section {
|
||||
margin-bottom: 32px;
|
||||
}
|
||||
|
||||
/* Multinivel: cada nivel es una fila independiente */
|
||||
.filtros-nivel {
|
||||
width: 100%;
|
||||
margin-bottom: 14px;
|
||||
align-items: center;
|
||||
animation: filtrosFadeIn .25s ease;
|
||||
}
|
||||
.filtros-nivel:last-child { margin-bottom: 32px; }
|
||||
.filtros-nivel .filtros-nivel-label {
|
||||
color: var(--ink-mute);
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
margin-right: 4px;
|
||||
padding: 0 6px;
|
||||
}
|
||||
@keyframes filtrosFadeIn {
|
||||
from { opacity: 0; transform: translateY(-4px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
.tag {
|
||||
padding: 8px 18px;
|
||||
background: var(--white);
|
||||
|
||||
+2
-2
@@ -9,7 +9,7 @@
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=DM+Serif+Display:ital@0;1&family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
|
||||
<link rel="stylesheet" href="estilos.css?v=4">
|
||||
<link rel="stylesheet" href="estilos.css?v=5">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -102,6 +102,6 @@
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script src="app.js?v=4"></script>
|
||||
<script src="app.js?v=5"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user