# Добавление стилей страницы if globalThis.stylFns and globalThis.stylFns['app/pages/Admin/Categories/index.styl'] styleElement = document.createElement('style') styleElement.type = 'text/css' styleElement.textContent = globalThis.stylFns['app/pages/Admin/Categories/index.styl'] document.head.appendChild(styleElement) else log '⚠️ Стили страницы категорий не найдены' { Category } = require 'app/types/data' CategoryService = require 'app/services/CategoryService' CategoryNode = require 'app/components/Admin/CategoryNode/index.coffee' MediaUpload = require 'app/components/Admin/MediaUpload/index.coffee' module.exports = { components: { 'category-node': CategoryNode 'media-upload': MediaUpload } data: -> { loading: false saving: false categories: [] editingCategory: null creatingNew: false categoryForm: { name: '' slug: '' parent: '' order: 0 image: '' description: '' } } computed: hierarchicalCategories: -> @buildHierarchy(@categories) flatCategories: -> @flattenCategories(@hierarchicalCategories) methods: # И обновите метод loadCategories: loadCategories: -> @loading = true try categoriesData = await CategoryService.getAllCategories() # Преобразуем данные из базы в объекты Category @categories = categoriesData.map (categoryData) -> new Category(categoryData) log '✅ Категории загружены: '+@categories.length catch error log '❌ Ошибка загрузки категорий: '+error.message @$emit('show-notification', 'Ошибка загрузки категорий', 'error') finally @loading = false # В методе buildHierarchy замените текущую реализацию на эту: buildHierarchy: (categories, parentId = null) -> hierarchy = [] # Фильтруем категории по parentId и сортируем по order categories .filter (cat) -> # Обрабатываем случаи когда parent может быть null, undefined или пустой строкой currentParent = cat.parent or null currentParent == parentId .sort (a, b) -> (a.order or 0) - (b.order or 0) .forEach (category) => # Создаем новый объект Category с данными из базы categoryData = new Category(category) # Рекурсивно строим детей children = @buildHierarchy(categories, category._id) if children.length > 0 categoryData.children = children hierarchy.push(categoryData) return hierarchy flattenCategories: (hierarchical, level = 0) -> flat = [] hierarchical.forEach (category) => flat.push({ ...category level: level name: '→ '.repeat(level) + category.name }) if category.children flat = flat.concat(@flattenCategories(category.children, level + 1)) return flat createCategory: -> @editingCategory = null @creatingNew = true @resetForm() editCategory: (category) -> @editingCategory = category @creatingNew = false @categoryForm = { name: category.name slug: category.slug parent: category.parent || '' order: category.order || 0 image: category.image || '' description: category.description || '' } cancelEdit: -> @editingCategory = null @creatingNew = false @resetForm() resetForm: -> @categoryForm = { name: '' slug: '' parent: '' order: 0 image: '' description: '' } saveCategory: -> if not @categoryForm.name.trim() @$emit('show-notification', 'Введите название категории', 'error') return @saving = true try categoryData = { ...@categoryForm type: 'category' domains: [window.location.hostname] active: true } if @editingCategory categoryData._id = @editingCategory._id categoryData._rev = @editingCategory._rev else categoryData._id = 'category:'+Date.now() if not categoryData.slug categoryData.slug = @slugify(categoryData.name) await CategoryService.saveCategory(categoryData) @$emit('show-notification', if @editingCategory then 'Категория обновлена' else 'Категория создана', 'success' ) @cancelEdit() @loadCategories() catch error log '❌ Ошибка сохранения категории: '+error.message @$emit('show-notification', 'Ошибка сохранения категории', 'error') finally @saving = false deleteCategory: (category) -> if not confirm('Удалить категорию "'+category.name+'"?') return try await CategoryService.deleteCategory(category._id) @$emit('show-notification', 'Категория удалена', 'success') @loadCategories() catch error log '❌ Ошибка удаления категории: '+error.message @$emit('show-notification', 'Ошибка удаления категории', 'error') moveCategory: (categoryId, newParentId, newIndex) -> log 'Перемещение категории: '+categoryId+' в '+newParentId+' на позицию '+newIndex # Здесь будет логика перемещения категорий через drag&drop onImageSelected: (imageUrl) -> @categoryForm.image = imageUrl onImageRemoved: -> @categoryForm.image = '' expandAll: -> # Логика раскрытия всех узлов дерева document.querySelectorAll('.category-node').forEach (node) -> node.classList.add('expanded') collapseAll: -> # Логика сворачивания всех узлов дерева document.querySelectorAll('.category-node').forEach (node) -> node.classList.remove('expanded') slugify: (text) -> text.toString().toLowerCase() .replace(/\s+/g, '-') .replace(/[^\w\-]+/g, '') .replace(/\-\-+/g, '-') .replace(/^-+/, '') .replace(/-+$/, '') mounted: -> @loadCategories() log '📂 Страница управления категориями загружена' render: (new Function '_ctx', '_cache', globalThis.renderFns['app/pages/Admin/Categories/index.pug'])() }