// JavaScript для страницы каталога позиций class CatalogManager { constructor() { this.warehouse = new WarehouseManager(); this.currentItems = []; this.filteredItems = []; this.currentPage = 1; this.itemsPerPage = 12; this.currentView = 'grid'; this.filters = {}; this.init(); } init() { $(document).ready(async () => { try { // Проверяем авторизацию if (!auth.isUserAuthenticated()) { console.log('Пользователь не авторизован, перенаправление на login.html'); window.location.href = 'login.html'; return; } console.log('Инициализация каталога для пользователя:', auth.getCurrentUser()?.name); // Загружаем каталог await this.loadCatalog(); // Загружаем категории в навигацию await this.loadCategoriesNav(); // Загружаем категории в выпадающее меню await this.loadCategoriesDropdown(); // Обновляем информацию о пользователе this.updateUserInfo(); // Привязываем события this.bindEvents(); // Инициализируем фильтры this.initializeFilters(); // Проверяем параметр категории в URL this.handleCategoryFromUrl(); // Обновляем права доступа this.updatePermissions(); } catch (error) { console.error('Ошибка инициализации:', error); auth.showNotification('Ошибка загрузки данных', 'danger'); } }); } bindEvents() { // Поиск и фильтры $('#searchInput').on('input', (e) => this.handleSearch(e.target.value)); $('#categoryFilter').on('change', (e) => this.handleCategoryFilter(e.target.value)); $('#priceMin, #priceMax').on('input', () => this.handlePriceFilter()); $('#inStockFilter, #lowStockFilter').on('change', () => this.applyFilters()); $('#clearFiltersBtn').on('click', () => this.clearFilters()); // Переключение вида $('input[name="viewMode"]').on('change', (e) => { this.currentView = e.target.id === 'gridView' ? 'grid' : 'list'; this.renderCatalog(); }); // Модальные окна $('#saveItemBtn').on('click', () => this.addNewItem()); $('#updateItemBtn').on('click', () => this.updateItem()); // Экспорт $('#exportBtn').on('click', () => this.exportCatalog()); // Обработчик выхода $('#logoutBtn').on('click', (e) => { e.preventDefault(); auth.logout(); window.location.href = 'login.html'; }); } // Загрузка каталога async loadCatalog() { try { this.showLoading(); // Загружаем позиции this.currentItems = await this.warehouse.getAllItems(); // Загружаем категории const categories = await this.warehouse.getCategories(); if (categories && categories.length > 0) { this.populateCategoryFilters(categories); } else { console.warn('Категории не найдены'); auth.showNotification('Категории не загружены', 'warning'); } // Применяем фильтры и рендерим this.applyFilters(); this.updateStatistics(); this.hideLoading(); } catch (error) { console.error('Ошибка при загрузке каталога:', error); auth.showNotification('Ошибка при загрузке каталога', 'danger'); this.hideLoading(); } } // Инициализация фильтров initializeFilters() { // Устанавливаем значения по умолчанию this.filters = { search: '', category: '', minPrice: null, maxPrice: null, inStock: false, lowStock: false }; } // Заполнение фильтра категорий populateCategoryFilters(categories) { if (!categories || categories.length === 0) { console.warn('Нет категорий для отображения'); return; } const categoryFilter = $('#categoryFilter'); const addItemCategory = $('#itemCategory'); const editItemCategory = $('#editItemCategory'); // Очищаем существующие опции (кроме первой) categoryFilter.find('option:not(:first)').remove(); addItemCategory.find('option:not(:first)').remove(); editItemCategory.find('option:not(:first)').remove(); // Добавляем категории categories.forEach(category => { if (category && category.id && category.name) { const option = ``; categoryFilter.append(option); addItemCategory.append(option); editItemCategory.append(option); } }); } // Обработка поиска handleSearch(query) { this.filters.search = query; this.applyFilters(); } // Обработка фильтра категории handleCategoryFilter(category) { this.filters.category = category; this.applyFilters(); } // Обработка фильтра цены handlePriceFilter() { this.filters.minPrice = $('#priceMin').val() ? parseFloat($('#priceMin').val()) : null; this.filters.maxPrice = $('#priceMax').val() ? parseFloat($('#priceMax').val()) : null; this.applyFilters(); } // Применение всех фильтров applyFilters() { this.filters.inStock = $('#inStockFilter').is(':checked'); this.filters.lowStock = $('#lowStockFilter').is(':checked'); // Фильтруем позиции this.filteredItems = this.currentItems.filter(item => { // Поиск по названию, описанию и штрих-коду if (this.filters.search) { const searchQuery = this.filters.search.toLowerCase(); const matchesSearch = item.name.toLowerCase().includes(searchQuery) || item.description.toLowerCase().includes(searchQuery) || item.barcode.includes(searchQuery); if (!matchesSearch) return false; } // Фильтр по категории if (this.filters.category && item.category !== this.filters.category) { return false; } // Фильтр по цене if (this.filters.minPrice && item.price < this.filters.minPrice) { return false; } if (this.filters.maxPrice && item.price > this.filters.maxPrice) { return false; } // Фильтр по наличию if (this.filters.inStock && item.quantity <= 0) { return false; } // Фильтр по низкому запасу if (this.filters.lowStock && item.quantity > item.minQuantity) { return false; } return true; }); this.currentPage = 1; this.renderCatalog(); this.updateStatistics(); } // Очистка фильтров clearFilters() { $('#searchInput').val(''); $('#categoryFilter').val(''); $('#priceMin').val(''); $('#priceMax').val(''); $('#inStockFilter').prop('checked', false); $('#lowStockFilter').prop('checked', false); this.initializeFilters(); this.applyFilters(); } // Рендеринг каталога renderCatalog() { const container = $('#catalogContainer'); container.empty(); if (this.filteredItems.length === 0) { container.html(`
Попробуйте изменить параметры поиска или фильтры
${item.description.substring(0, 60)}${item.description.length > 60 ? '...' : ''}
Загрузка каталога...