Добавлены новые модели и мутации для навигационных категорий, включая создание, обновление и удаление. Обновлены типы GraphQL и резолверы для обработки навигационных категорий, что улучшает структуру данных и функциональность. В боковое меню добавлен новый элемент для навигации по категориям. Реализован кэш для оптимизации запросов к API, что повышает производительность приложения.

This commit is contained in:
Bivekich
2025-07-13 21:42:04 +03:00
parent db29525da5
commit ac122411e0
12 changed files with 1681 additions and 95 deletions

View File

@ -302,6 +302,8 @@ export const CategoryForm = ({
</div>
</div>
{/* Настройки */}
<div className="space-y-3">
<h3 className="text-sm font-medium">Настройки</h3>

View File

@ -0,0 +1,381 @@
'use client'
import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { Textarea } from '@/components/ui/textarea'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { useQuery } from '@apollo/client'
import { GET_PARTSINDEX_CATEGORIES } from '@/lib/graphql/queries'
import { Loader2, Upload, X, Image as ImageIcon, Folder, FolderOpen } from 'lucide-react'
interface PartsIndexCategory {
id: string
name: string
image?: string
groups?: PartsIndexGroup[]
}
interface PartsIndexGroup {
id: string
name: string
image?: string
subgroups?: PartsIndexGroup[]
}
interface NavigationCategory {
id?: string
partsIndexCatalogId: string
partsIndexGroupId?: string
icon?: string
isHidden: boolean
sortOrder: number
}
interface NavigationCategoryFormProps {
category?: NavigationCategory | null
onSubmit: (data: any) => void
onCancel: () => void
isLoading?: boolean
}
export default function NavigationCategoryForm({
category,
onSubmit,
onCancel,
isLoading = false
}: NavigationCategoryFormProps) {
const [formData, setFormData] = useState({
partsIndexCatalogId: '',
partsIndexGroupId: '',
icon: '',
isHidden: false,
sortOrder: 0
})
const [selectedCatalog, setSelectedCatalog] = useState<PartsIndexCategory | null>(null)
const [selectedGroup, setSelectedGroup] = useState<PartsIndexGroup | null>(null)
// Загрузка категорий PartsIndex
const { data: categoriesData, loading: categoriesLoading, error: categoriesError } = useQuery(
GET_PARTSINDEX_CATEGORIES,
{
variables: { lang: 'ru' },
errorPolicy: 'all'
}
)
const categories = categoriesData?.partsIndexCategoriesWithGroups || []
// Заполнение формы при редактировании
useEffect(() => {
if (category) {
setFormData({
partsIndexCatalogId: category.partsIndexCatalogId || '',
partsIndexGroupId: category.partsIndexGroupId || '',
icon: category.icon || '',
isHidden: category.isHidden || false,
sortOrder: category.sortOrder || 0
})
// Находим выбранный каталог и группу
const catalog = categories.find(c => c.id === category.partsIndexCatalogId)
if (catalog) {
setSelectedCatalog(catalog)
if (category.partsIndexGroupId && catalog.groups) {
const group = findGroupById(catalog.groups, category.partsIndexGroupId)
setSelectedGroup(group || null)
}
}
}
}, [category, categories])
// Рекурсивный поиск группы по ID
const findGroupById = (groups: PartsIndexGroup[], groupId: string): PartsIndexGroup | null => {
for (const group of groups) {
if (group.id === groupId) {
return group
}
if (group.subgroups && group.subgroups.length > 0) {
const found = findGroupById(group.subgroups, groupId)
if (found) return found
}
}
return null
}
// Получение всех групп из каталога (включая подгруппы)
const getAllGroups = (groups: PartsIndexGroup[], level = 0): Array<PartsIndexGroup & { level: number }> => {
const result: Array<PartsIndexGroup & { level: number }> = []
groups.forEach(group => {
result.push({ ...group, level })
if (group.subgroups && group.subgroups.length > 0) {
result.push(...getAllGroups(group.subgroups, level + 1))
}
})
return result
}
const handleInputChange = (field: string, value: any) => {
setFormData(prev => ({ ...prev, [field]: value }))
}
const handleCatalogSelect = (catalogId: string) => {
const catalog = categories.find(c => c.id === catalogId)
setSelectedCatalog(catalog || null)
setSelectedGroup(null)
handleInputChange('partsIndexCatalogId', catalogId)
handleInputChange('partsIndexGroupId', '')
}
const handleGroupSelect = (groupId: string) => {
if (groupId === '__CATALOG_ROOT__') {
setSelectedGroup(null)
handleInputChange('partsIndexGroupId', '')
} else if (selectedCatalog?.groups) {
const group = findGroupById(selectedCatalog.groups, groupId)
setSelectedGroup(group || null)
handleInputChange('partsIndexGroupId', groupId)
}
}
const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (file) {
const reader = new FileReader()
reader.onload = (e) => {
const result = e.target?.result as string
handleInputChange('icon', result)
}
reader.readAsDataURL(file)
}
}
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (!formData.partsIndexCatalogId) {
alert('Выберите каталог')
return
}
onSubmit(formData)
}
const getDisplayName = () => {
if (selectedGroup) {
return `${selectedCatalog?.name}${selectedGroup.name}`
}
return selectedCatalog?.name || 'Выберите категорию'
}
if (categoriesLoading) {
return (
<Card>
<CardContent className="flex items-center justify-center py-8">
<Loader2 className="h-8 w-8 animate-spin text-blue-600" />
<span className="ml-2">Загрузка категорий PartsIndex...</span>
</CardContent>
</Card>
)
}
if (categoriesError) {
return (
<Card>
<CardContent className="py-8">
<div className="text-center text-red-600">
Ошибка загрузки категорий PartsIndex: {categoriesError.message}
</div>
</CardContent>
</Card>
)
}
return (
<Card>
<CardHeader>
<CardTitle>
{category ? 'Редактировать иконку категории' : 'Добавить иконку для категории'}
</CardTitle>
<p className="text-sm text-gray-600">
Выберите категорию из PartsIndex и загрузите иконку для отображения в навигации сайта
</p>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-6">
{/* Выбор каталога */}
<div>
<Label htmlFor="catalog">Каталог PartsIndex</Label>
<Select value={formData.partsIndexCatalogId} onValueChange={handleCatalogSelect}>
<SelectTrigger className="mt-1">
<SelectValue placeholder="Выберите каталог из PartsIndex" />
</SelectTrigger>
<SelectContent>
{categories.map((catalog) => (
<SelectItem key={catalog.id} value={catalog.id}>
<div className="flex items-center gap-2">
<Folder className="h-4 w-4 text-blue-600" />
{catalog.name}
{catalog.groups && (
<Badge variant="secondary" className="ml-2">
{catalog.groups.length} групп
</Badge>
)}
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Выбор группы (если есть группы в каталоге) */}
{selectedCatalog?.groups && selectedCatalog.groups.length > 0 && (
<div>
<Label htmlFor="group">Группа (необязательно)</Label>
<p className="text-xs text-gray-500 mb-2">
Оставьте пустым для добавления иконки всему каталогу
</p>
<Select value={formData.partsIndexGroupId || '__CATALOG_ROOT__'} onValueChange={handleGroupSelect}>
<SelectTrigger className="mt-1">
<SelectValue placeholder="Выберите группу или оставьте пустым" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__CATALOG_ROOT__">
<div className="flex items-center gap-2">
<FolderOpen className="h-4 w-4 text-gray-400" />
Весь каталог &quot;{selectedCatalog.name}&quot;
</div>
</SelectItem>
{getAllGroups(selectedCatalog.groups).map((group) => (
<SelectItem key={group.id} value={group.id}>
<div className="flex items-center gap-2" style={{ paddingLeft: `${group.level * 16}px` }}>
<Folder className="h-4 w-4 text-orange-600" />
{group.name}
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
{/* Предварительный просмотр выбранной категории */}
{formData.partsIndexCatalogId && (
<div className="p-4 bg-gray-50 rounded-lg">
<div className="flex items-center gap-2 text-sm font-medium">
<ImageIcon className="h-4 w-4 text-blue-600" />
Выбранная категория:
</div>
<div className="mt-1 text-sm text-gray-600">
{getDisplayName()}
</div>
</div>
)}
{/* Загрузка иконки */}
<div>
<Label htmlFor="icon">Иконка категории</Label>
<p className="text-xs text-gray-500 mb-2">
Небольшая иконка для отображения в навигационном меню (рекомендуется 32x32 пикселя)
</p>
<div className="space-y-2">
{formData.icon && (
<div className="relative inline-block">
<img
src={formData.icon}
alt="Превью иконки"
className="w-16 h-16 object-cover rounded-lg border"
/>
<Button
type="button"
variant="destructive"
size="sm"
className="absolute -top-2 -right-2 h-6 w-6 p-0"
onClick={() => handleInputChange('icon', '')}
>
<X className="h-3 w-3" />
</Button>
</div>
)}
<div className="flex items-center gap-2">
<Input
type="file"
accept="image/*"
onChange={handleImageUpload}
className="hidden"
id="icon-upload"
/>
<Button
type="button"
variant="outline"
onClick={() => document.getElementById('icon-upload')?.click()}
>
<Upload className="h-4 w-4 mr-2" />
Загрузить иконку
</Button>
</div>
</div>
</div>
{/* Настройки отображения */}
<div className="space-y-4">
<div className="flex items-center space-x-2">
<Switch
id="isHidden"
checked={formData.isHidden}
onCheckedChange={(checked) => handleInputChange('isHidden', checked)}
/>
<Label htmlFor="isHidden" className="text-sm font-medium">
Скрыть категорию в навигации
</Label>
</div>
<div>
<Label htmlFor="sortOrder">Порядок сортировки</Label>
<Input
type="number"
id="sortOrder"
value={formData.sortOrder}
onChange={(e) => handleInputChange('sortOrder', parseInt(e.target.value) || 0)}
className="mt-1"
placeholder="0"
/>
<p className="text-xs text-gray-500 mt-1">
Меньшее число = выше в списке
</p>
</div>
</div>
{/* Кнопки */}
<div className="flex gap-2 pt-4">
<Button
type="submit"
disabled={isLoading || !formData.partsIndexCatalogId}
className="flex-1"
>
{isLoading && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
{category ? 'Сохранить изменения' : 'Добавить иконку'}
</Button>
<Button
type="button"
variant="outline"
onClick={onCancel}
disabled={isLoading}
>
Отмена
</Button>
</div>
</form>
</CardContent>
</Card>
)
}

View File

@ -0,0 +1,377 @@
'use client'
import { useState } from 'react'
import { useQuery, useMutation } from '@apollo/client'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Alert, AlertDescription } from '@/components/ui/alert'
import {
GET_NAVIGATION_CATEGORIES,
GET_PARTSINDEX_CATEGORIES
} from '@/lib/graphql/queries'
import {
CREATE_NAVIGATION_CATEGORY,
UPDATE_NAVIGATION_CATEGORY,
DELETE_NAVIGATION_CATEGORY
} from '@/lib/graphql/mutations'
import { Loader2, Plus, Edit, Trash2, Image as ImageIcon, Folder, Settings, Eye, EyeOff } from 'lucide-react'
import NavigationCategoryForm from './NavigationCategoryForm'
interface NavigationCategory {
id: string
partsIndexCatalogId: string
partsIndexGroupId?: string
icon?: string
isHidden: boolean
sortOrder: number
name: string
catalogName: string
groupName?: string
}
interface PartsIndexCategory {
id: string
name: string
image?: string
groups?: PartsIndexGroup[]
}
interface PartsIndexGroup {
id: string
name: string
image?: string
subgroups?: PartsIndexGroup[]
}
export default function NavigationCategoryTree() {
const [editingCategory, setEditingCategory] = useState<NavigationCategory | null>(null)
const [showForm, setShowForm] = useState(false)
// Загрузка навигационных категорий (с иконками)
const {
data: navigationData,
loading: navigationLoading,
error: navigationError,
refetch: refetchNavigation
} = useQuery(GET_NAVIGATION_CATEGORIES, {
errorPolicy: 'all'
})
// Загрузка категорий PartsIndex
const {
data: partsIndexData,
loading: partsIndexLoading,
error: partsIndexError
} = useQuery(GET_PARTSINDEX_CATEGORIES, {
variables: { lang: 'ru' },
errorPolicy: 'all'
})
// Мутации
const [createCategory, { loading: creating }] = useMutation(CREATE_NAVIGATION_CATEGORY, {
onCompleted: () => {
refetchNavigation()
handleCloseForm()
},
onError: (error) => {
console.error('Ошибка создания категории:', error)
alert('Не удалось создать иконку для категории')
}
})
const [updateCategory, { loading: updating }] = useMutation(UPDATE_NAVIGATION_CATEGORY, {
onCompleted: () => {
refetchNavigation()
handleCloseForm()
},
onError: (error) => {
console.error('Ошибка обновления категории:', error)
alert('Не удалось обновить иконку категории')
}
})
const [deleteCategory, { loading: deleting }] = useMutation(DELETE_NAVIGATION_CATEGORY, {
onCompleted: () => {
refetchNavigation()
},
onError: (error) => {
console.error('Ошибка удаления категории:', error)
alert('Не удалось удалить иконку категории')
}
})
const navigationCategories = navigationData?.navigationCategories || []
const partsIndexCategories = partsIndexData?.partsIndexCategoriesWithGroups || []
const handleSubmit = async (formData: any) => {
try {
if (editingCategory) {
await updateCategory({
variables: {
id: editingCategory.id,
input: formData
}
})
} else {
await createCategory({
variables: {
input: formData
}
})
}
} catch (error) {
console.error('Ошибка сохранения:', error)
}
}
const handleEdit = (category: NavigationCategory) => {
setEditingCategory(category)
setShowForm(true)
}
const handleDelete = async (category: NavigationCategory) => {
if (confirm(`Удалить иконку для категории "${category.name}"?`)) {
await deleteCategory({
variables: { id: category.id }
})
}
}
const handleCloseForm = () => {
setEditingCategory(null)
setShowForm(false)
}
// Функция для получения полного пути категории
const getCategoryPath = (catalogId: string, groupId?: string) => {
const catalog = partsIndexCategories.find(c => c.id === catalogId)
if (!catalog) return 'Неизвестная категория'
if (!groupId) return catalog.name
// Рекурсивный поиск группы
const findGroup = (groups: PartsIndexGroup[]): PartsIndexGroup | null => {
for (const group of groups) {
if (group.id === groupId) return group
if (group.subgroups) {
const found = findGroup(group.subgroups)
if (found) return found
}
}
return null
}
const group = catalog.groups ? findGroup(catalog.groups) : null
return group ? `${catalog.name}${group.name}` : catalog.name
}
// Проверка есть ли иконка для категории
const hasIcon = (catalogId: string, groupId?: string) => {
return navigationCategories.some(nav =>
nav.partsIndexCatalogId === catalogId &&
nav.partsIndexGroupId === groupId
)
}
// Получение иконки для категории
const getIcon = (catalogId: string, groupId?: string) => {
return navigationCategories.find(nav =>
nav.partsIndexCatalogId === catalogId &&
nav.partsIndexGroupId === groupId
)
}
if (showForm) {
return (
<NavigationCategoryForm
category={editingCategory}
onSubmit={handleSubmit}
onCancel={handleCloseForm}
isLoading={creating || updating}
/>
)
}
if (navigationLoading || partsIndexLoading) {
return (
<Card>
<CardContent className="flex items-center justify-center py-8">
<Loader2 className="h-8 w-8 animate-spin text-blue-600" />
<span className="ml-2">Загрузка категорий...</span>
</CardContent>
</Card>
)
}
if (navigationError || partsIndexError) {
return (
<Alert variant="destructive">
<AlertDescription>
Ошибка загрузки категорий: {navigationError?.message || partsIndexError?.message}
</AlertDescription>
</Alert>
)
}
return (
<div className="space-y-6">
{/* Заголовок */}
<div className="flex justify-between items-center">
<div>
<h2 className="text-2xl font-bold">Иконки навигации</h2>
<p className="text-gray-600">
Привязка иконок к категориям PartsIndex для отображения в навигации сайта
</p>
</div>
<Button onClick={() => setShowForm(true)}>
<Plus className="h-4 w-4 mr-2" />
Добавить иконку
</Button>
</div>
{/* Статистика */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<Card>
<CardContent className="p-4">
<div className="flex items-center gap-2">
<Folder className="h-5 w-5 text-blue-600" />
<div>
<div className="text-sm text-gray-600">Каталогов PartsIndex</div>
<div className="text-2xl font-bold">{partsIndexCategories.length}</div>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center gap-2">
<ImageIcon className="h-5 w-5 text-green-600" />
<div>
<div className="text-sm text-gray-600">С иконками</div>
<div className="text-2xl font-bold">{navigationCategories.length}</div>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center gap-2">
<Settings className="h-5 w-5 text-orange-600" />
<div>
<div className="text-sm text-gray-600">Активных</div>
<div className="text-2xl font-bold">
{navigationCategories.filter(cat => !cat.isHidden).length}
</div>
</div>
</div>
</CardContent>
</Card>
</div>
{/* Список категорий с иконками */}
{navigationCategories.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Категории с иконками</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3">
{navigationCategories
.sort((a, b) => a.sortOrder - b.sortOrder)
.map((navCategory) => (
<div
key={navCategory.id}
className="flex items-center justify-between p-4 border rounded-lg hover:bg-gray-50"
>
<div className="flex items-center gap-3">
{/* Иконка */}
<div className="w-12 h-12 border rounded-lg flex items-center justify-center overflow-hidden">
{navCategory.icon ? (
<img
src={navCategory.icon}
alt={navCategory.name}
className="w-full h-full object-cover"
/>
) : (
<ImageIcon className="h-6 w-6 text-gray-400" />
)}
</div>
{/* Информация */}
<div>
<div className="font-medium">{navCategory.name}</div>
<div className="text-sm text-gray-600">
{getCategoryPath(navCategory.partsIndexCatalogId, navCategory.partsIndexGroupId)}
</div>
<div className="flex items-center gap-2 mt-1">
<Badge variant="secondary" className="text-xs">
Сортировка: {navCategory.sortOrder}
</Badge>
{navCategory.isHidden && (
<Badge variant="destructive" className="text-xs">
<EyeOff className="h-3 w-3 mr-1" />
Скрыта
</Badge>
)}
{!navCategory.isHidden && (
<Badge variant="default" className="text-xs">
<Eye className="h-3 w-3 mr-1" />
Видима
</Badge>
)}
</div>
</div>
</div>
{/* Действия */}
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => handleEdit(navCategory)}
disabled={deleting}
>
<Edit className="h-4 w-4" />
</Button>
<Button
variant="destructive"
size="sm"
onClick={() => handleDelete(navCategory)}
disabled={deleting}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
))}
</div>
</CardContent>
</Card>
)}
{/* Инструкции */}
<Card>
<CardHeader>
<CardTitle>Как использовать</CardTitle>
</CardHeader>
<CardContent className="space-y-3 text-sm text-gray-600">
<p>
<strong>1. Выберите каталог:</strong> Из списка каталогов PartsIndex выберите тот, для которого хотите добавить иконку.
</p>
<p>
<strong>2. Выберите группу (необязательно):</strong> Если хотите добавить иконку для конкретной группы внутри каталога, выберите её. Иначе иконка будет применена ко всему каталогу.
</p>
<p>
<strong>3. Загрузите иконку:</strong> Выберите небольшое изображение (рекомендуется 32x32 пикселя) которое будет отображаться в навигации сайта.
</p>
<p>
<strong>4. Настройте отображение:</strong> Установите порядок сортировки и видимость категории в навигации.
</p>
</CardContent>
</Card>
</div>
)
}

View File

@ -34,6 +34,11 @@ const navigationItems = [
href: '/dashboard/catalog',
icon: Package,
},
{
title: 'Навигация сайта',
href: '/dashboard/navigation',
icon: Star,
},
{
title: 'Товары главной',
href: '/dashboard/homepage-products',