fix(pos): rewrite catalog.js to match design system HTML structure + add cart sidebar
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
// /home/Autopartes/pos/static/js/catalog.js
|
||||
// Catalog UI: browsable inventory with cart, barcode scanner, external lookup
|
||||
// Aligned with design-system catalog.html IDs and class names.
|
||||
|
||||
(function () {
|
||||
'use strict';
|
||||
@@ -10,99 +11,201 @@
|
||||
|
||||
const headers = { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' };
|
||||
|
||||
// ─── DOM refs (design-system IDs) ───
|
||||
const productGrid = document.getElementById('productGrid');
|
||||
const emptyState = document.getElementById('emptyState');
|
||||
const emptyTitle = document.getElementById('emptyStateTitle');
|
||||
const emptySubtitle = document.getElementById('emptyStateSubtitle');
|
||||
const searchInput = document.getElementById('inp-part');
|
||||
const partSearchBtn = document.getElementById('partSearchBtn');
|
||||
const cartSidebar = document.getElementById('cartSidebar');
|
||||
const cartOverlay = document.getElementById('cartOverlay');
|
||||
const cartItemsEl = document.getElementById('cartItems');
|
||||
const cartEmptyEl = document.getElementById('cartEmpty');
|
||||
const cartSubtotalEl = document.getElementById('cartSubtotal');
|
||||
const cartTaxEl = document.getElementById('cartTax');
|
||||
const cartTotalEl = document.getElementById('cartTotal');
|
||||
const cartBadge = document.getElementById('cartBadge');
|
||||
const checkoutBtn = document.getElementById('checkoutBtn');
|
||||
const paginationNav = document.querySelector('.pagination');
|
||||
|
||||
// ─── State ───
|
||||
let currentPage = 1;
|
||||
let currentFilters = {};
|
||||
let cartItems = JSON.parse(localStorage.getItem('pos_cart') || '[]');
|
||||
let barcodeBuffer = '';
|
||||
let barcodeTimeout = null;
|
||||
let catalogItemsMap = {}; // id -> item for cart lookup
|
||||
|
||||
// ─── API helpers ───
|
||||
async function apiFetch(url, opts) {
|
||||
const resp = await fetch(url, Object.assign({ headers: headers }, opts || {}));
|
||||
if (resp.status === 401) { localStorage.removeItem('pos_token'); window.location.href = '/pos/login'; return null; }
|
||||
return resp.json();
|
||||
try {
|
||||
var resp = await fetch(url, Object.assign({ headers: headers }, opts || {}));
|
||||
if (resp.status === 401) {
|
||||
localStorage.removeItem('pos_token');
|
||||
window.location.href = '/pos/login';
|
||||
return null;
|
||||
}
|
||||
return resp.json();
|
||||
} catch (e) {
|
||||
console.error('API fetch error:', e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Catalog loading ───
|
||||
async function loadCatalog(page, filters) {
|
||||
currentPage = page || 1;
|
||||
currentFilters = filters || currentFilters;
|
||||
const params = new URLSearchParams({ page: currentPage, per_page: 30 });
|
||||
var params = new URLSearchParams({ page: currentPage, per_page: 30 });
|
||||
if (currentFilters.q) params.set('q', currentFilters.q);
|
||||
if (currentFilters.category) params.set('category', currentFilters.category);
|
||||
if (currentFilters.brand) params.set('brand', currentFilters.brand);
|
||||
if (currentFilters.vehicle_brand) params.set('vehicle_brand', currentFilters.vehicle_brand);
|
||||
|
||||
const data = await apiFetch(API + '/catalog/search?' + params.toString());
|
||||
var data = await apiFetch(API + '/catalog/search?' + params.toString());
|
||||
if (!data) return;
|
||||
|
||||
renderGrid(data.data || []);
|
||||
var items = data.data || [];
|
||||
renderGrid(items);
|
||||
renderPagination(data.pagination || {});
|
||||
renderActiveFilters();
|
||||
updateResultsCount(data.pagination || {});
|
||||
}
|
||||
|
||||
function renderGrid(items) {
|
||||
const grid = document.getElementById('catalogGrid');
|
||||
// Clear demo/hardcoded cards
|
||||
productGrid.innerHTML = '';
|
||||
|
||||
if (!items.length) {
|
||||
grid.innerHTML = '<div class="empty-state"><p>No se encontraron productos</p><button onclick="checkExternalAvailability()" style="margin-top:12px; padding:8px 16px; cursor:pointer;">Buscar en bodegas Nexus</button></div>';
|
||||
productGrid.style.display = 'none';
|
||||
emptyState.classList.add('is-visible');
|
||||
emptyTitle.textContent = 'No se encontraron productos';
|
||||
emptySubtitle.textContent = currentFilters.q
|
||||
? 'No hay resultados para "' + currentFilters.q + '". Intenta con otro termino.'
|
||||
: 'Intenta con otro termino de busqueda o verifica el numero de parte';
|
||||
return;
|
||||
}
|
||||
grid.innerHTML = items.map(function (it) {
|
||||
var stockClass = it.stock <= 0 ? 'stock-badge--zero' : (it.low_stock ? 'stock-badge--low' : 'stock-badge--ok');
|
||||
var stockLabel = it.stock <= 0 ? 'Agotado' : it.stock + ' ' + (it.unit || 'PZA');
|
||||
return '<div class="card catalog-card" onclick="window._addToCart(' + it.id + ')" data-id="' + it.id + '">' +
|
||||
(it.image_url ? '<img src="' + it.image_url + '" alt="" style="width:100%;height:120px;object-fit:contain;margin-bottom:8px;">' : '<div style="height:120px;background:#f0f0f0;display:flex;align-items:center;justify-content:center;margin-bottom:8px;border-radius:4px;color:#aaa;">Sin imagen</div>') +
|
||||
'<div style="font-weight:600;font-size:0.9rem;margin-bottom:4px;">' + escHtml(it.name) + '</div>' +
|
||||
'<div style="font-size:0.8rem;color:#666;margin-bottom:4px;">' + escHtml(it.part_number) + (it.brand ? ' · ' + escHtml(it.brand) : '') + '</div>' +
|
||||
'<div style="display:flex;justify-content:space-between;align-items:center;">' +
|
||||
'<span style="font-weight:700;font-size:1rem;">$' + fmt(it.price_1) + '</span>' +
|
||||
'<span class="stock-badge ' + stockClass + '">' + stockLabel + '</span>' +
|
||||
'</div></div>';
|
||||
}).join('');
|
||||
|
||||
// Store items for cart lookup
|
||||
window._catalogItems = {};
|
||||
items.forEach(function (it) { window._catalogItems[it.id] = it; });
|
||||
emptyState.classList.remove('is-visible');
|
||||
productGrid.style.display = '';
|
||||
|
||||
catalogItemsMap = {};
|
||||
items.forEach(function (it) { catalogItemsMap[it.id] = it; });
|
||||
|
||||
productGrid.innerHTML = items.map(function (it) {
|
||||
var stockClass, stockLabel;
|
||||
if (it.stock <= 0) {
|
||||
stockClass = 'stock-out';
|
||||
stockLabel = 'Agotado';
|
||||
} else if (it.low_stock) {
|
||||
stockClass = 'stock-low';
|
||||
stockLabel = 'Ultimas ' + it.stock;
|
||||
} else {
|
||||
stockClass = 'stock-ok';
|
||||
stockLabel = 'En stock';
|
||||
}
|
||||
|
||||
var isOut = it.stock <= 0;
|
||||
var imgHtml;
|
||||
if (it.image_url) {
|
||||
imgHtml = '<img src="' + escHtml(it.image_url) + '" alt="' + escHtml(it.name) + '" style="width:100%;height:100%;object-fit:contain;">';
|
||||
} else {
|
||||
imgHtml = '<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M8 7h8M8 12h8M8 17h5"/></svg>' +
|
||||
'<span class="product-card__image-label" aria-hidden="true">IMG</span>';
|
||||
}
|
||||
|
||||
return '<article class="product-card" role="listitem" data-id="' + it.id + '">' +
|
||||
'<div class="product-card__image">' +
|
||||
imgHtml +
|
||||
'<div class="stock-badge ' + stockClass + '" role="status">' + stockLabel + '</div>' +
|
||||
'</div>' +
|
||||
'<div class="product-card__body">' +
|
||||
(it.category_name ? '<div class="product-card__category">' + escHtml(it.category_name) + '</div>' : '') +
|
||||
'<div class="product-card__name">' + escHtml(it.name) + '</div>' +
|
||||
'<div class="product-card__oem" title="Numero de parte">' + escHtml(it.part_number || '') + '</div>' +
|
||||
'<div class="product-card__brand">' +
|
||||
'<span>' + escHtml(it.brand || '') + '</span>' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'<div class="product-card__footer">' +
|
||||
'<div class="product-card__pricing">' +
|
||||
'<div class="product-card__price">$' + fmt(it.price_1) + '</div>' +
|
||||
'<div class="product-card__price-unit">MXN / ' + escHtml(it.unit || 'PZA') + '</div>' +
|
||||
'</div>' +
|
||||
(isOut
|
||||
? '<button class="btn-add" disabled style="opacity:0.45;cursor:not-allowed;" aria-label="Producto agotado">' +
|
||||
'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="M4.93 4.93l14.14 14.14"/></svg> Agotado</button>'
|
||||
: '<button class="btn-add" onclick="CatalogApp.addToCart(' + it.id + ')" aria-label="Agregar ' + escHtml(it.name) + ' al carrito">' +
|
||||
'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg> Agregar</button>'
|
||||
) +
|
||||
'</div>' +
|
||||
'</article>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function renderPagination(pg) {
|
||||
var el = document.getElementById('pagination');
|
||||
if (!pg || pg.total_pages <= 1) { el.innerHTML = ''; return; }
|
||||
var html = '<button ' + (pg.page <= 1 ? 'disabled' : 'onclick="window._loadPage(' + (pg.page - 1) + ')"') + '>« Anterior</button>';
|
||||
html += '<span style="padding:6px 12px; font-size:0.85rem;">' + pg.page + ' / ' + pg.total_pages + '</span>';
|
||||
html += '<button ' + (pg.page >= pg.total_pages ? 'disabled' : 'onclick="window._loadPage(' + (pg.page + 1) + ')"') + '>Siguiente »</button>';
|
||||
el.innerHTML = html;
|
||||
if (!paginationNav) return;
|
||||
if (!pg || pg.total_pages <= 1) {
|
||||
paginationNav.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
|
||||
var html = '';
|
||||
|
||||
// Previous button
|
||||
if (pg.page <= 1) {
|
||||
html += '<button class="page-item page-item--wide is-disabled" disabled aria-label="Pagina anterior">' +
|
||||
'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="15,18 9,12 15,6"/></svg> Anterior</button>';
|
||||
} else {
|
||||
html += '<button class="page-item page-item--wide" onclick="CatalogApp.loadPage(' + (pg.page - 1) + ')" aria-label="Pagina anterior">' +
|
||||
'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="15,18 9,12 15,6"/></svg> Anterior</button>';
|
||||
}
|
||||
|
||||
// Page numbers
|
||||
var pages = buildPageNumbers(pg.page, pg.total_pages);
|
||||
pages.forEach(function (p) {
|
||||
if (p === '...') {
|
||||
html += '<span class="page-ellipsis" aria-hidden="true">…</span>';
|
||||
} else if (p === pg.page) {
|
||||
html += '<button class="page-item is-active" aria-label="Pagina ' + p + ', actual" aria-current="page">' + p + '</button>';
|
||||
} else {
|
||||
html += '<button class="page-item" onclick="CatalogApp.loadPage(' + p + ')" aria-label="Ir a pagina ' + p + '">' + p + '</button>';
|
||||
}
|
||||
});
|
||||
|
||||
// Next button
|
||||
if (pg.page >= pg.total_pages) {
|
||||
html += '<button class="page-item page-item--wide is-disabled" disabled aria-label="Pagina siguiente">Siguiente ' +
|
||||
'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9,18 15,12 9,6"/></svg></button>';
|
||||
} else {
|
||||
html += '<button class="page-item page-item--wide" onclick="CatalogApp.loadPage(' + (pg.page + 1) + ')" aria-label="Pagina siguiente">Siguiente ' +
|
||||
'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9,18 15,12 9,6"/></svg></button>';
|
||||
}
|
||||
|
||||
paginationNav.innerHTML = html;
|
||||
}
|
||||
|
||||
function renderActiveFilters() {
|
||||
var el = document.getElementById('activeFilters');
|
||||
var chips = [];
|
||||
if (currentFilters.category) chips.push('<span class="chip active" onclick="window._removeFilter(\'category\')">Cat: ' + currentFilters.category + ' ×</span>');
|
||||
if (currentFilters.brand) chips.push('<span class="chip active" onclick="window._removeFilter(\'brand\')">' + escHtml(currentFilters.brand) + ' ×</span>');
|
||||
if (currentFilters.vehicle_brand) chips.push('<span class="chip active" onclick="window._removeFilter(\'vehicle_brand\')">Vehiculo: ' + escHtml(currentFilters.vehicle_brand) + ' ×</span>');
|
||||
el.innerHTML = chips.join('');
|
||||
function buildPageNumbers(current, total) {
|
||||
if (total <= 7) {
|
||||
var arr = [];
|
||||
for (var i = 1; i <= total; i++) arr.push(i);
|
||||
return arr;
|
||||
}
|
||||
var pages = [1];
|
||||
if (current > 3) pages.push('...');
|
||||
for (var j = Math.max(2, current - 1); j <= Math.min(total - 1, current + 1); j++) {
|
||||
pages.push(j);
|
||||
}
|
||||
if (current < total - 2) pages.push('...');
|
||||
pages.push(total);
|
||||
return pages;
|
||||
}
|
||||
|
||||
// ─── Sidebar filters ───
|
||||
async function loadCategories() {
|
||||
var data = await apiFetch(API + '/catalog/categories');
|
||||
if (!data) return;
|
||||
var ul = document.getElementById('categoryList');
|
||||
var cats = data.data || [];
|
||||
if (!cats.length) { ul.innerHTML = '<li style="color:#999;">Sin categorias</li>'; return; }
|
||||
ul.innerHTML = '<li onclick="window._filterCat(null)" class="' + (!currentFilters.category ? 'active' : '') + '">Todas</li>' +
|
||||
cats.map(function (c) { return '<li onclick="window._filterCat(' + c.id + ')" class="' + (currentFilters.category == c.id ? 'active' : '') + '">Cat #' + c.id + ' <small>(' + c.count + ')</small></li>'; }).join('');
|
||||
}
|
||||
|
||||
async function loadBrands() {
|
||||
var data = await apiFetch(API + '/catalog/brands');
|
||||
if (!data) return;
|
||||
var ul = document.getElementById('brandList');
|
||||
var brands = data.data || [];
|
||||
if (!brands.length) { ul.innerHTML = '<li style="color:#999;">Sin marcas</li>'; return; }
|
||||
ul.innerHTML = '<li onclick="window._filterBrand(null)" class="' + (!currentFilters.brand ? 'active' : '') + '">Todas</li>' +
|
||||
brands.map(function (b) { return '<li onclick="window._filterBrand(\'' + escHtml(b.name) + '\')" class="' + (currentFilters.brand === b.name ? 'active' : '') + '">' + escHtml(b.name) + ' <small>(' + b.count + ')</small></li>'; }).join('');
|
||||
function updateResultsCount(pg) {
|
||||
var el = document.querySelector('.results-count');
|
||||
if (!el || !pg) return;
|
||||
var total = pg.total || 0;
|
||||
el.innerHTML = '<strong>' + total.toLocaleString('es-MX') + '</strong> partes encontradas';
|
||||
}
|
||||
|
||||
// ─── Barcode scanner ───
|
||||
@@ -112,10 +215,13 @@
|
||||
addToCart(data);
|
||||
}
|
||||
|
||||
// Listen for rapid keypress (barcode scanners type fast, then Enter)
|
||||
document.addEventListener('keydown', function (e) {
|
||||
if (e.key === 'F1') { e.preventDefault(); document.getElementById('searchInput').focus(); return; }
|
||||
if (document.activeElement.tagName === 'INPUT' || document.activeElement.tagName === 'TEXTAREA') return;
|
||||
if (e.key === 'F1') {
|
||||
e.preventDefault();
|
||||
if (searchInput) searchInput.focus();
|
||||
return;
|
||||
}
|
||||
if (document.activeElement.tagName === 'INPUT' || document.activeElement.tagName === 'TEXTAREA' || document.activeElement.tagName === 'SELECT') return;
|
||||
if (e.key === 'Enter' && barcodeBuffer.length >= 4) {
|
||||
lookupBarcode(barcodeBuffer.trim());
|
||||
barcodeBuffer = '';
|
||||
@@ -129,6 +235,11 @@
|
||||
});
|
||||
|
||||
// ─── Cart ───
|
||||
function addToCartById(id) {
|
||||
var it = catalogItemsMap[id];
|
||||
if (it) addToCart(it);
|
||||
}
|
||||
|
||||
function addToCart(item) {
|
||||
var existing = cartItems.find(function (c) { return c.id === item.id; });
|
||||
if (existing) {
|
||||
@@ -136,12 +247,16 @@
|
||||
} else {
|
||||
cartItems.push({
|
||||
id: item.id, part_number: item.part_number, name: item.name,
|
||||
brand: item.brand, price: item.price_1, tax_rate: item.tax_rate || 0.16,
|
||||
brand: item.brand, price: item.price_1 || item.price, tax_rate: item.tax_rate || 0.16,
|
||||
unit: item.unit || 'PZA', stock: item.stock, quantity: 1
|
||||
});
|
||||
}
|
||||
saveCart();
|
||||
renderCart();
|
||||
// Brief open to show item was added
|
||||
if (!cartSidebar.classList.contains('open')) {
|
||||
toggleCart();
|
||||
}
|
||||
}
|
||||
|
||||
function removeFromCart(index) {
|
||||
@@ -169,60 +284,59 @@
|
||||
}
|
||||
|
||||
function renderCart() {
|
||||
var badge = document.getElementById('cartBadge');
|
||||
var total = cartItems.reduce(function (s, c) { return s + c.quantity; }, 0);
|
||||
badge.textContent = total;
|
||||
badge.style.display = total > 0 ? 'flex' : 'none';
|
||||
|
||||
var container = document.getElementById('cartItems');
|
||||
var empty = document.getElementById('cartEmpty');
|
||||
var checkoutBtn = document.getElementById('checkoutBtn');
|
||||
if (cartBadge) {
|
||||
cartBadge.textContent = total;
|
||||
cartBadge.style.display = total > 0 ? 'flex' : 'none';
|
||||
}
|
||||
|
||||
if (!cartItems.length) {
|
||||
container.innerHTML = '';
|
||||
empty.style.display = 'block';
|
||||
checkoutBtn.disabled = true;
|
||||
document.getElementById('cartSubtotal').textContent = '$0.00';
|
||||
document.getElementById('cartTax').textContent = '$0.00';
|
||||
document.getElementById('cartTotal').textContent = '$0.00';
|
||||
cartItemsEl.innerHTML = '';
|
||||
cartEmptyEl.style.display = 'block';
|
||||
if (checkoutBtn) checkoutBtn.disabled = true;
|
||||
cartSubtotalEl.textContent = '$0.00';
|
||||
cartTaxEl.textContent = '$0.00';
|
||||
cartTotalEl.textContent = '$0.00';
|
||||
return;
|
||||
}
|
||||
|
||||
empty.style.display = 'none';
|
||||
checkoutBtn.disabled = false;
|
||||
cartEmptyEl.style.display = 'none';
|
||||
if (checkoutBtn) checkoutBtn.disabled = false;
|
||||
|
||||
var subtotal = 0;
|
||||
var tax = 0;
|
||||
container.innerHTML = cartItems.map(function (c, i) {
|
||||
cartItemsEl.innerHTML = cartItems.map(function (c, i) {
|
||||
var lineTotal = c.price * c.quantity;
|
||||
var lineTax = lineTotal * c.tax_rate;
|
||||
subtotal += lineTotal;
|
||||
tax += lineTax;
|
||||
return '<div class="cart-item">' +
|
||||
'<div style="flex:1;">' +
|
||||
'<div style="font-weight:600;font-size:0.85rem;">' + escHtml(c.name) + '</div>' +
|
||||
'<div style="font-size:0.75rem;color:#666;">' + escHtml(c.part_number) + '</div>' +
|
||||
'<div style="font-weight:600;font-size:0.85rem;color:var(--color-text-primary);">' + escHtml(c.name) + '</div>' +
|
||||
'<div style="font-size:0.75rem;color:var(--color-text-muted);">' + escHtml(c.part_number) + '</div>' +
|
||||
'<div style="margin-top:4px;display:flex;align-items:center;gap:6px;">' +
|
||||
'<button onclick="window._updateQty(' + i + ',' + (c.quantity - 1) + ')" style="width:24px;height:24px;border:1px solid #ddd;background:#fff;border-radius:4px;cursor:pointer;">-</button>' +
|
||||
'<span style="font-weight:600;">' + c.quantity + '</span>' +
|
||||
'<button onclick="window._updateQty(' + i + ',' + (c.quantity + 1) + ')" style="width:24px;height:24px;border:1px solid #ddd;background:#fff;border-radius:4px;cursor:pointer;">+</button>' +
|
||||
'<button onclick="CatalogApp.updateQty(' + i + ',' + (c.quantity - 1) + ')" style="width:24px;height:24px;border:1px solid var(--color-border);background:var(--color-bg-base);border-radius:var(--radius-sm);cursor:pointer;color:var(--color-text-primary);">-</button>' +
|
||||
'<span style="font-weight:600;color:var(--color-text-primary);">' + c.quantity + '</span>' +
|
||||
'<button onclick="CatalogApp.updateQty(' + i + ',' + (c.quantity + 1) + ')" style="width:24px;height:24px;border:1px solid var(--color-border);background:var(--color-bg-base);border-radius:var(--radius-sm);cursor:pointer;color:var(--color-text-primary);">+</button>' +
|
||||
'</div></div>' +
|
||||
'<div style="text-align:right;">' +
|
||||
'<div style="font-weight:600;">$' + fmt(lineTotal) + '</div>' +
|
||||
'<button onclick="window._removeFromCart(' + i + ')" style="font-size:0.75rem;color:#ef4444;background:none;border:none;cursor:pointer;margin-top:4px;">Quitar</button>' +
|
||||
'<div style="font-weight:600;color:var(--color-text-primary);">$' + fmt(lineTotal) + '</div>' +
|
||||
'<button onclick="CatalogApp.removeFromCart(' + i + ')" style="font-size:0.75rem;color:var(--color-error,#ef4444);background:none;border:none;cursor:pointer;margin-top:4px;">Quitar</button>' +
|
||||
'</div></div>';
|
||||
}).join('');
|
||||
|
||||
document.getElementById('cartSubtotal').textContent = '$' + fmt(subtotal);
|
||||
document.getElementById('cartTax').textContent = '$' + fmt(tax);
|
||||
document.getElementById('cartTotal').textContent = '$' + fmt(subtotal + tax);
|
||||
cartSubtotalEl.textContent = '$' + fmt(subtotal);
|
||||
cartTaxEl.textContent = '$' + fmt(tax);
|
||||
cartTotalEl.textContent = '$' + fmt(subtotal + tax);
|
||||
}
|
||||
|
||||
function toggleCart() {
|
||||
document.getElementById('cartSidebar').classList.toggle('open');
|
||||
var isOpen = cartSidebar.classList.toggle('open');
|
||||
if (cartOverlay) cartOverlay.classList.toggle('open', isOpen);
|
||||
}
|
||||
|
||||
function goToCheckout() {
|
||||
if (!cartItems.length) return;
|
||||
localStorage.setItem('pos_cart', JSON.stringify(cartItems));
|
||||
window.location.href = '/pos/sale';
|
||||
}
|
||||
@@ -231,19 +345,17 @@
|
||||
async function checkExternalAvailability(partNumber) {
|
||||
var pn = partNumber || currentFilters.q || '';
|
||||
if (!pn) return;
|
||||
var section = document.getElementById('externalSection');
|
||||
var results = document.getElementById('externalResults');
|
||||
section.style.display = 'block';
|
||||
results.innerHTML = '<p>Buscando en bodegas...</p>';
|
||||
alert('Buscando "' + pn + '" en bodegas Nexus...');
|
||||
|
||||
var data = await apiFetch(API + '/catalog/external-availability/' + encodeURIComponent(pn));
|
||||
if (!data || !data.data || !data.data.length) {
|
||||
results.innerHTML = '<p>No se encontraron resultados externos para "' + escHtml(pn) + '"</p>';
|
||||
alert('No se encontraron resultados externos para "' + pn + '"');
|
||||
return;
|
||||
}
|
||||
results.innerHTML = '<ul>' + data.data.map(function (r) {
|
||||
return '<li><strong>' + escHtml(r.name || r.part_number || pn) + '</strong> — Stock: ' + (r.stock || 'N/A') + '</li>';
|
||||
}).join('') + '</ul>';
|
||||
var msg = data.data.map(function (r) {
|
||||
return (r.name || r.part_number || pn) + ' - Stock: ' + (r.stock || 'N/A');
|
||||
}).join('\n');
|
||||
alert('Resultados externos:\n' + msg);
|
||||
}
|
||||
|
||||
// ─── Helpers ───
|
||||
@@ -251,43 +363,73 @@
|
||||
function escHtml(s) { if (!s) return ''; var d = document.createElement('div'); d.textContent = s; return d.innerHTML; }
|
||||
|
||||
// ─── Search input ───
|
||||
var searchInput = document.getElementById('searchInput');
|
||||
var searchTimeout = null;
|
||||
searchInput.addEventListener('input', function () {
|
||||
clearTimeout(searchTimeout);
|
||||
searchTimeout = setTimeout(function () {
|
||||
currentFilters.q = searchInput.value.trim();
|
||||
loadCatalog(1, currentFilters);
|
||||
}, 350);
|
||||
});
|
||||
searchInput.addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (searchInput) {
|
||||
searchInput.addEventListener('input', function () {
|
||||
clearTimeout(searchTimeout);
|
||||
currentFilters.q = searchInput.value.trim();
|
||||
searchTimeout = setTimeout(function () {
|
||||
currentFilters.q = searchInput.value.trim();
|
||||
loadCatalog(1, currentFilters);
|
||||
}, 300);
|
||||
});
|
||||
searchInput.addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
clearTimeout(searchTimeout);
|
||||
currentFilters.q = searchInput.value.trim();
|
||||
loadCatalog(1, currentFilters);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Part search button ───
|
||||
if (partSearchBtn) {
|
||||
partSearchBtn.addEventListener('click', function () {
|
||||
if (searchInput) {
|
||||
currentFilters.q = searchInput.value.trim();
|
||||
loadCatalog(1, currentFilters);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Filter chips ───
|
||||
document.querySelectorAll('[data-chip]').forEach(function (chip) {
|
||||
chip.addEventListener('click', function () {
|
||||
var isActive = chip.classList.contains('is-active');
|
||||
// Deactivate all chips first for single-select behavior
|
||||
document.querySelectorAll('[data-chip]').forEach(function (c) {
|
||||
c.classList.remove('is-active');
|
||||
c.setAttribute('aria-pressed', 'false');
|
||||
});
|
||||
if (!isActive) {
|
||||
chip.classList.add('is-active');
|
||||
chip.setAttribute('aria-pressed', 'true');
|
||||
currentFilters.category = chip.dataset.chip;
|
||||
} else {
|
||||
delete currentFilters.category;
|
||||
}
|
||||
loadCatalog(1, currentFilters);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Expose globals for inline handlers ───
|
||||
window._addToCart = function (id) {
|
||||
var it = window._catalogItems && window._catalogItems[id];
|
||||
if (it) addToCart(it);
|
||||
// ─── Expose globals for inline onclick handlers ───
|
||||
window.CatalogApp = {
|
||||
toggleCart: toggleCart,
|
||||
goToCheckout: goToCheckout,
|
||||
addToCart: addToCartById,
|
||||
removeFromCart: removeFromCart,
|
||||
updateQty: updateQuantity,
|
||||
clearCart: clearCartFn,
|
||||
loadPage: function (p) { loadCatalog(p); },
|
||||
checkExternal: checkExternalAvailability
|
||||
};
|
||||
window._loadPage = function (p) { loadCatalog(p); };
|
||||
window._removeFilter = function (key) { delete currentFilters[key]; loadCatalog(1); loadCategories(); loadBrands(); };
|
||||
window._filterCat = function (id) { if (id) currentFilters.category = id; else delete currentFilters.category; loadCatalog(1); loadCategories(); };
|
||||
window._filterBrand = function (name) { if (name) currentFilters.brand = name; else delete currentFilters.brand; loadCatalog(1); loadBrands(); };
|
||||
window._removeFromCart = removeFromCart;
|
||||
window._updateQty = updateQuantity;
|
||||
|
||||
// Also keep legacy window._ handlers for backward compat
|
||||
window.toggleCart = toggleCart;
|
||||
window.goToCheckout = goToCheckout;
|
||||
window.clearCart = clearCartFn;
|
||||
window.checkExternalAvailability = checkExternalAvailability;
|
||||
|
||||
// ─── Init ───
|
||||
renderCart();
|
||||
loadCatalog(1, {});
|
||||
loadCategories();
|
||||
loadBrands();
|
||||
})();
|
||||
|
||||
Reference in New Issue
Block a user