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

This commit is contained in:
Bivekich
2025-07-17 16:36:07 +03:00
parent 6a94d51032
commit f377fbab5f
21 changed files with 3958 additions and 34 deletions

View File

@ -118,6 +118,12 @@ model Organization {
services Service[]
supplies Supply[]
// Товары (только для оптовиков)
products Product[]
// Корзины
carts Cart[]
@@map("organizations")
}
@ -274,3 +280,106 @@ model Supply {
@@map("supplies")
}
// Модель категорий товаров
model Category {
id String @id @default(cuid())
name String @unique // Название категории
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Связь с товарами
products Product[]
@@map("categories")
}
// Модель товаров (для оптовиков)
model Product {
id String @id @default(cuid())
// Основные поля
name String // Название товара
article String // Артикул/номер записи
description String? // Описание
// Цена и количество
price Decimal @db.Decimal(12,2) // Цена за единицу
quantity Int @default(0) // Количество в наличии
// Основные характеристики
category Category? @relation(fields: [categoryId], references: [id])
categoryId String? // ID категории
brand String? // Бренд
// Дополнительные характеристики (необязательные)
color String? // Цвет
size String? // Размер
weight Decimal? @db.Decimal(8,3) // Вес в кг
dimensions String? // Габариты (ДxШxВ)
material String? // Материал
// Изображения (JSON массив URL-ов в S3)
images Json @default("[]") // Массив URL изображений
mainImage String? // URL главного изображения
// Статус товара
isActive Boolean @default(true) // Активен ли товар
// Временные метки
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Связь с организацией (только оптовики)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
organizationId String
// Связь с элементами корзины
cartItems CartItem[]
// Уникальность артикула в рамках организации
@@unique([organizationId, article])
@@map("products")
}
// Модель корзины
model Cart {
id String @id @default(cuid())
// Связь с организацией (только покупатель может иметь корзину)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
organizationId String @unique // У каждой организации может быть только одна корзина
// Элементы корзины
items CartItem[]
// Временные метки
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@map("carts")
}
// Модель элемента корзины
model CartItem {
id String @id @default(cuid())
// Связь с корзиной
cart Cart @relation(fields: [cartId], references: [id], onDelete: Cascade)
cartId String
// Связь с товаром
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
productId String
// Количество товара в корзине
quantity Int @default(1)
// Временные метки
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Уникальность: один товар может быть только один раз в корзине
@@unique([cartId, productId])
@@map("cart_items")
}

View File

@ -42,12 +42,25 @@ export async function POST(request: NextRequest) {
const file = formData.get('file') as File
const userId = formData.get('userId') as string
const messageType = formData.get('messageType') as string // 'IMAGE' или 'FILE'
const type = formData.get('type') as string // Для товаров: 'product'
if (!file || !userId || !messageType) {
return NextResponse.json(
{ error: 'File, userId and messageType are required' },
{ status: 400 }
)
// Проверяем параметры в зависимости от типа загрузки
if (type === 'product') {
// Для товаров нужен только файл
if (!file) {
return NextResponse.json(
{ error: 'File is required' },
{ status: 400 }
)
}
} else {
// Для мессенджера нужны все параметры
if (!file || !userId || !messageType) {
return NextResponse.json(
{ error: 'File, userId and messageType are required' },
{ status: 400 }
)
}
}
// Проверяем, что файл не пустой
@ -66,8 +79,8 @@ export async function POST(request: NextRequest) {
)
}
// Проверяем тип файла в зависимости от типа сообщения
const isImage = messageType === 'IMAGE'
// Проверяем тип файла в зависимости от типа загрузки
const isImage = type === 'product' || messageType === 'IMAGE'
const allowedTypes = isImage ? ALLOWED_IMAGE_TYPES : [...ALLOWED_IMAGE_TYPES, ...ALLOWED_FILE_TYPES]
if (!allowedTypes.includes(file.type)) {
@ -96,16 +109,41 @@ export async function POST(request: NextRequest) {
.replace(/_{2,}/g, '_') // Убираем множественные подчеркивания
.toLowerCase() // Приводим к нижнему регистру
const folder = isImage ? 'images' : 'files'
const key = `${folder}/${userId}/${timestamp}-${safeFileName}`
// Определяем папку и ключ в зависимости от типа загрузки
let folder: string
let key: string
if (type === 'product') {
folder = 'products'
key = `${folder}/${timestamp}-${safeFileName}`
} else {
folder = isImage ? 'images' : 'files'
key = `${folder}/${userId}/${timestamp}-${safeFileName}`
}
// Конвертируем файл в Buffer
const buffer = Buffer.from(await file.arrayBuffer())
// Очищаем метаданные от недопустимых символов
const cleanOriginalName = file.name.replace(/[^\w\s.-]/g, '_')
const cleanUserId = userId.replace(/[^\w-]/g, '')
const cleanMessageType = messageType.replace(/[^\w]/g, '')
// Подготавливаем метаданные в зависимости от типа загрузки
let metadata: Record<string, string>
if (type === 'product') {
metadata = {
originalname: cleanOriginalName,
uploadtype: 'product'
}
} else {
const cleanUserId = userId.replace(/[^\w-]/g, '')
const cleanMessageType = messageType.replace(/[^\w]/g, '')
metadata = {
originalname: cleanOriginalName,
uploadedby: cleanUserId,
messagetype: cleanMessageType
}
}
// Загружаем в S3
const command = new PutObjectCommand({
@ -114,11 +152,7 @@ export async function POST(request: NextRequest) {
Body: buffer,
ContentType: file.type,
ACL: 'public-read',
Metadata: {
originalname: cleanOriginalName,
uploadedby: cleanUserId,
messagetype: cleanMessageType
}
Metadata: metadata
})
await s3Client.send(command)
@ -126,15 +160,22 @@ export async function POST(request: NextRequest) {
// Возвращаем URL файла и метаданные
const url = `https://s3.twcstorage.ru/${BUCKET_NAME}/${key}`
return NextResponse.json({
const response: Record<string, unknown> = {
success: true,
url,
fileUrl: url, // Изменяем на fileUrl для совместимости с формой товаров
url, // Оставляем для совместимости с мессенджером
key,
originalName: file.name,
size: file.size,
type: file.type,
messageType
})
type: file.type
}
// Добавляем messageType только для мессенджера
if (messageType) {
response.messageType = messageType
}
return NextResponse.json(response)
} catch (error) {
console.error('Error uploading file:', error)

View File

@ -0,0 +1,10 @@
import { AuthGuard } from "@/components/auth-guard"
import { WarehouseDashboard } from "@/components/warehouse/warehouse-dashboard"
export default function WarehousePage() {
return (
<AuthGuard>
<WarehouseDashboard />
</AuthGuard>
)
}

View File

@ -42,6 +42,20 @@ export function ConfirmationStep({ data, onConfirm, onBack }: ConfirmationStepPr
const { registerFulfillmentOrganization, registerSellerOrganization } = useAuth()
// Преобразование типа кабинета в тип организации
const getOrganizationType = (cabinetType: string): 'FULFILLMENT' | 'LOGIST' | 'WHOLESALE' => {
switch (cabinetType) {
case 'fulfillment':
return 'FULFILLMENT'
case 'logist':
return 'LOGIST'
case 'wholesale':
return 'WHOLESALE'
default:
return 'FULFILLMENT'
}
}
const formatPhone = (phone: string) => {
return phone || "+7 (___) ___-__-__"
}
@ -58,7 +72,8 @@ export function ConfirmationStep({ data, onConfirm, onBack }: ConfirmationStepPr
if ((data.cabinetType === 'fulfillment' || data.cabinetType === 'logist' || data.cabinetType === 'wholesale') && data.inn) {
result = await registerFulfillmentOrganization(
data.phone.replace(/\D/g, ''),
data.inn
data.inn,
getOrganizationType(data.cabinetType)
)
} else if (data.cabinetType === 'seller') {
result = await registerSellerOrganization({

View File

@ -0,0 +1,109 @@
"use client"
import { useQuery } from '@apollo/client'
import { Card } from '@/components/ui/card'
import { Sidebar } from '@/components/dashboard/sidebar'
import { CartItems } from './cart-items'
import { CartSummary } from './cart-summary'
import { GET_MY_CART } from '@/graphql/queries'
import { ShoppingCart, Package } from 'lucide-react'
export function CartDashboard() {
const { data, loading, error } = useQuery(GET_MY_CART)
const cart = data?.myCart
const hasItems = cart?.items && cart.items.length > 0
if (loading) {
return (
<div className="h-screen bg-gradient-smooth flex overflow-hidden">
<Sidebar />
<main className="flex-1 ml-56 px-6 py-4 overflow-hidden">
<div className="h-full flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-16 w-16 border-4 border-white border-t-transparent mx-auto mb-4"></div>
<p className="text-white/70">Загружаем корзину...</p>
</div>
</div>
</main>
</div>
)
}
if (error) {
return (
<div className="h-screen bg-gradient-smooth flex overflow-hidden">
<Sidebar />
<main className="flex-1 ml-56 px-6 py-4 overflow-hidden">
<div className="h-full flex items-center justify-center">
<div className="text-center">
<ShoppingCart className="h-16 w-16 text-red-400/40 mx-auto mb-4" />
<p className="text-red-400">Ошибка загрузки корзины</p>
<p className="text-white/40 text-sm mt-2">{error.message}</p>
</div>
</div>
</main>
</div>
)
}
return (
<div className="h-screen bg-gradient-smooth flex overflow-hidden">
<Sidebar />
<main className="flex-1 ml-56 px-6 py-4 overflow-hidden">
<div className="h-full w-full flex flex-col">
{/* Заголовок */}
<div className="flex items-center space-x-3 mb-6">
<ShoppingCart className="h-6 w-6 text-purple-400" />
<div>
<h1 className="text-2xl font-bold text-white">Корзина</h1>
<p className="text-white/60">
{hasItems
? `${cart.totalItems} товаров на сумму ${new Intl.NumberFormat('ru-RU', { style: 'currency', currency: 'RUB' }).format(cart.totalPrice)}`
: 'Ваша корзина пуста'
}
</p>
</div>
</div>
{/* Основной контент */}
<div className="flex-1 overflow-hidden">
{hasItems ? (
<div className="h-full grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Товары в корзине */}
<div className="lg:col-span-2">
<Card className="glass-card h-full overflow-hidden">
<CartItems cart={cart} />
</Card>
</div>
{/* Сводка заказа */}
<div className="lg:col-span-1">
<Card className="glass-card h-fit">
<CartSummary cart={cart} />
</Card>
</div>
</div>
) : (
<Card className="glass-card h-full overflow-hidden p-8">
<div className="h-full flex flex-col items-center justify-center text-center">
<Package className="h-24 w-24 text-white/20 mb-6" />
<h2 className="text-xl font-semibold text-white mb-2">Корзина пуста</h2>
<p className="text-white/60 mb-6 max-w-md">
Добавьте товары из маркета, чтобы оформить заказ
</p>
<button
onClick={() => window.location.href = '/market'}
className="bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white px-6 py-3 rounded-lg font-medium transition-all"
>
Перейти в маркет
</button>
</div>
</Card>
)}
</div>
</div>
</main>
</div>
)
}

View File

@ -0,0 +1,389 @@
"use client"
import { useState } from 'react'
import { useMutation } from '@apollo/client'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
Trash2,
AlertTriangle,
Package,
Store,
Minus,
Plus
} from 'lucide-react'
import { OrganizationAvatar } from '@/components/market/organization-avatar'
import { Input } from '@/components/ui/input'
import Image from 'next/image'
import { UPDATE_CART_ITEM, REMOVE_FROM_CART, CLEAR_CART } from '@/graphql/mutations'
import { GET_MY_CART } from '@/graphql/queries'
import { toast } from 'sonner'
interface CartItem {
id: string
quantity: number
totalPrice: number
isAvailable: boolean
availableQuantity: number
product: {
id: string
name: string
article: string
price: number
quantity: number
images: string[]
mainImage?: string
organization: {
id: string
name?: string
fullName?: string
inn: string
}
}
}
interface Cart {
id: string
items: CartItem[]
totalPrice: number
totalItems: number
}
interface CartItemsProps {
cart: Cart
}
export function CartItems({ cart }: CartItemsProps) {
const [loadingItems, setLoadingItems] = useState<Set<string>>(new Set())
const [updateCartItem] = useMutation(UPDATE_CART_ITEM, {
refetchQueries: [{ query: GET_MY_CART }],
onCompleted: (data) => {
if (data.updateCartItem.success) {
toast.success(data.updateCartItem.message)
} else {
toast.error(data.updateCartItem.message)
}
},
onError: (error) => {
toast.error('Ошибка при обновлении заявки')
console.error('Error updating cart item:', error)
}
})
const [removeFromCart] = useMutation(REMOVE_FROM_CART, {
refetchQueries: [{ query: GET_MY_CART }],
onCompleted: (data) => {
if (data.removeFromCart.success) {
toast.success(data.removeFromCart.message)
} else {
toast.error(data.removeFromCart.message)
}
},
onError: (error) => {
toast.error('Ошибка при удалении заявки')
console.error('Error removing from cart:', error)
}
})
const [clearCart] = useMutation(CLEAR_CART, {
refetchQueries: [{ query: GET_MY_CART }],
onCompleted: () => {
toast.success('Заявки очищены')
},
onError: (error) => {
toast.error('Ошибка при очистке заявок')
console.error('Error clearing cart:', error)
}
})
const updateQuantity = async (productId: string, newQuantity: number) => {
if (newQuantity <= 0) return
setLoadingItems(prev => new Set(prev).add(productId))
try {
await updateCartItem({
variables: {
productId,
quantity: newQuantity
}
})
} finally {
setLoadingItems(prev => {
const newSet = new Set(prev)
newSet.delete(productId)
return newSet
})
}
}
const removeItem = async (productId: string) => {
setLoadingItems(prev => new Set(prev).add(productId))
try {
await removeFromCart({
variables: { productId }
})
} finally {
setLoadingItems(prev => {
const newSet = new Set(prev)
newSet.delete(productId)
return newSet
})
}
}
const handleClearCart = async () => {
if (confirm('Вы уверены, что хотите очистить все заявки?')) {
await clearCart()
}
}
const formatPrice = (price: number) => {
return new Intl.NumberFormat('ru-RU', {
style: 'currency',
currency: 'RUB'
}).format(price)
}
const unavailableItems = cart.items.filter(item => !item.isAvailable)
const availableItems = cart.items.filter(item => item.isAvailable)
// Группировка товаров по поставщикам
const groupedItems = cart.items.reduce((groups, item) => {
const orgId = item.product.organization.id
if (!groups[orgId]) {
groups[orgId] = {
organization: item.product.organization,
items: [],
totalPrice: 0,
totalItems: 0
}
}
groups[orgId].items.push(item)
groups[orgId].totalPrice += item.totalPrice
groups[orgId].totalItems += item.quantity
return groups
}, {} as Record<string, {
organization: CartItem['product']['organization'],
items: CartItem[],
totalPrice: number,
totalItems: number
}>)
const supplierGroups = Object.values(groupedItems)
return (
<div className="p-6 h-full flex flex-col">
{/* Заголовок с кнопкой очистки */}
<div className="flex items-center justify-between mb-6">
<h2 className="text-xl font-semibold text-white">Заявки на товары</h2>
{cart.items.length > 0 && (
<Button
onClick={handleClearCart}
variant="outline"
size="sm"
className="border-red-500/30 text-red-400 hover:bg-red-500/10"
>
<Trash2 className="h-4 w-4 mr-2" />
Очистить заявки
</Button>
)}
</div>
{/* Предупреждение о недоступных товарах */}
{unavailableItems.length > 0 && (
<div className="mb-6 p-4 bg-orange-500/10 border border-orange-500/20 rounded-lg">
<div className="flex items-center space-x-2 text-orange-400">
<AlertTriangle className="h-4 w-4" />
<span className="text-sm font-medium">
{unavailableItems.length} заявок недоступно для оформления
</span>
</div>
</div>
)}
{/* Группы поставщиков */}
<div className="flex-1 overflow-auto space-y-8">
{supplierGroups.map((group) => (
<div key={group.organization.id} className="space-y-4">
{/* Заголовок поставщика */}
<div className="bg-gradient-to-r from-purple-600/20 via-purple-500/10 to-transparent border border-purple-500/20 rounded-xl p-5">
<div className="flex items-center justify-between">
<div className="flex items-center space-x-4">
<OrganizationAvatar organization={group.organization} size="md" />
<div>
<h3 className="text-lg font-semibold text-white mb-1">
{group.organization.name || group.organization.fullName || `ИНН ${group.organization.inn}`}
</h3>
<div className="flex items-center space-x-3 text-sm text-white/60">
<span className="flex items-center space-x-1">
<Package className="h-4 w-4" />
<span>{group.totalItems} товаров</span>
</span>
<span></span>
<span className="font-medium text-purple-300">
{formatPrice(group.totalPrice)}
</span>
</div>
</div>
</div>
<Badge
variant="secondary"
className="bg-purple-500/20 text-purple-300 px-3 py-1 text-sm font-medium"
>
{group.items.length} заявок
</Badge>
</div>
</div>
{/* Товары этого поставщика */}
<div className="space-y-3">
{group.items.map((item) => {
const isLoading = loadingItems.has(item.product.id)
const mainImage = item.product.images?.[0] || item.product.mainImage
return (
<div
key={item.id}
className={`bg-white/5 backdrop-blur border border-white/10 rounded-xl transition-all hover:bg-white/8 hover:border-white/20 ${
!item.isAvailable ? 'opacity-60' : ''
}`}
>
{/* Информация о поставщике в карточке товара */}
<div className="px-4 py-2 bg-white/5 border-b border-white/10 rounded-t-xl">
<div className="flex items-center space-x-2 text-xs text-white/60">
<Store className="h-3 w-3" />
<span>Поставщик:</span>
<span className="text-white/80 font-medium">
{item.product.organization.name || item.product.organization.fullName || `ИНН ${item.product.organization.inn}`}
</span>
</div>
</div>
{/* Основное содержимое карточки */}
<div className="p-5">
<div className="flex space-x-4">
{/* Изображение товара */}
<div className="flex-shrink-0">
<div className="w-20 h-20 bg-white/5 rounded-xl overflow-hidden border border-white/10 shadow-lg">
{mainImage ? (
<Image
src={mainImage}
alt={item.product.name}
width={80}
height={80}
className="w-full h-full object-cover"
/>
) : (
<div className="w-full h-full flex items-center justify-center">
<Package className="h-8 w-8 text-white/20" />
</div>
)}
</div>
</div>
{/* Информация о товаре */}
<div className="flex-1 min-w-0">
{/* Название и артикул */}
<div className="mb-3">
<h4 className="text-base font-semibold text-white mb-1 line-clamp-2">
{item.product.name}
</h4>
<p className="text-sm text-white/50">
Артикул: {item.product.article}
</p>
</div>
{/* Статус доступности */}
{!item.isAvailable && (
<Badge className="bg-red-500/20 text-red-300 text-xs mb-3 border border-red-500/30">
Недоступно
</Badge>
)}
{/* Нижняя секция: управление количеством и цена */}
<div className="flex items-center justify-between">
{/* Управление количеством */}
<div className="flex items-center space-x-3">
<div className="flex items-center space-x-2">
<span className="text-sm text-white/60 font-medium">Количество:</span>
<div className="flex items-center space-x-2">
<Button
onClick={() => updateQuantity(item.product.id, item.quantity - 1)}
disabled={isLoading || !item.isAvailable || item.quantity <= 1}
variant="outline"
size="sm"
className="h-8 w-8 p-0 border-white/20 text-white/70 hover:bg-white/10"
>
<Minus className="h-3 w-3" />
</Button>
<Input
type="number"
min="1"
max={item.availableQuantity}
value={item.quantity}
onChange={(e) => {
const value = parseInt(e.target.value) || 1
if (value >= 1 && value <= item.availableQuantity && !isLoading && item.isAvailable) {
updateQuantity(item.product.id, value)
}
}}
disabled={isLoading || !item.isAvailable}
className="w-16 h-8 text-sm text-center bg-white/5 border border-white/20 rounded-lg text-white focus:border-purple-400/50 focus:bg-white/10"
/>
<Button
onClick={() => updateQuantity(item.product.id, item.quantity + 1)}
disabled={isLoading || !item.isAvailable || item.quantity >= item.availableQuantity}
variant="outline"
size="sm"
className="h-8 w-8 p-0 border-white/20 text-white/70 hover:bg-white/10"
>
<Plus className="h-3 w-3" />
</Button>
</div>
</div>
<span className="text-sm text-white/40">
из {item.availableQuantity} доступно
</span>
</div>
{/* Цена и кнопка удаления */}
<div className="flex items-center space-x-4">
<div className="text-right">
<div className="text-lg font-bold text-purple-300 mb-1">
{formatPrice(item.totalPrice)}
</div>
<div className="text-sm text-white/50">
{formatPrice(item.product.price)} за шт.
</div>
</div>
<Button
onClick={() => removeItem(item.product.id)}
disabled={isLoading}
variant="outline"
size="sm"
className="text-red-400 border-red-500/30 hover:bg-red-500/10 hover:text-red-300 h-9 w-9 p-0"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
</div>
</div>
</div>
</div>
)
})}
</div>
</div>
))}
</div>
</div>
)
}

View File

@ -0,0 +1,242 @@
"use client"
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import {
ShoppingCart,
AlertTriangle,
CheckCircle,
Info
} from 'lucide-react'
interface CartItem {
id: string
quantity: number
totalPrice: number
isAvailable: boolean
availableQuantity: number
product: {
id: string
name: string
article: string
price: number
quantity: number
organization: {
id: string
name?: string
fullName?: string
inn: string
}
}
}
interface Cart {
id: string
items: CartItem[]
totalPrice: number
totalItems: number
}
interface CartSummaryProps {
cart: Cart
}
export function CartSummary({ cart }: CartSummaryProps) {
const [isProcessingOrder, setIsProcessingOrder] = useState(false)
const formatPrice = (price: number) => {
return new Intl.NumberFormat('ru-RU', {
style: 'currency',
currency: 'RUB'
}).format(price)
}
// Анализ товаров в корзине
const availableItems = cart.items.filter(item => item.isAvailable)
const unavailableItems = cart.items.filter(item => !item.isAvailable)
const availableTotal = availableItems.reduce((sum, item) => sum + item.totalPrice, 0)
const availableItemsCount = availableItems.reduce((sum, item) => sum + item.quantity, 0)
// Группировка по продавцам
const sellerGroups = availableItems.reduce((groups, item) => {
const sellerId = item.product.organization.id
if (!groups[sellerId]) {
groups[sellerId] = {
organization: item.product.organization,
items: [],
total: 0
}
}
groups[sellerId].items.push(item)
groups[sellerId].total += item.totalPrice
return groups
}, {} as Record<string, {
organization: CartItem['product']['organization']
items: CartItem[]
total: number
}>)
const sellerCount = Object.keys(sellerGroups).length
const canOrder = availableItems.length > 0
const handleOrder = () => {
if (!canOrder) return
setIsProcessingOrder(true)
// Здесь будет логика отправки заявок
setTimeout(() => {
alert('Функция отправки заявок будет реализована в следующих версиях')
setIsProcessingOrder(false)
}, 1000)
}
const getOrganizationName = (org: CartItem['product']['organization']) => {
return org.name || org.fullName || 'Неизвестная организация'
}
return (
<div className="p-6">
<h2 className="text-lg font-semibold text-white mb-4">Сводка заявок</h2>
<div className="space-y-4">
{/* Общая информация */}
<div className="space-y-2">
<div className="flex justify-between text-sm">
<span className="text-white/70">Всего заявок:</span>
<span className="text-white">{cart.totalItems}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-white/70">Готово к отправке:</span>
<span className="text-white">{availableItemsCount}</span>
</div>
{unavailableItems.length > 0 && (
<div className="flex justify-between text-sm">
<span className="text-red-400">Недоступно:</span>
<span className="text-red-400">{unavailableItems.length}</span>
</div>
)}
</div>
<Separator className="bg-white/10" />
{/* Информация о поставщиках */}
{sellerCount > 0 && (
<div className="space-y-3">
<div className="flex items-center space-x-2 text-sm text-white/70">
<Info className="h-4 w-4" />
<span>Поставщики ({sellerCount}):</span>
</div>
<div className="space-y-2">
{Object.values(sellerGroups).map((group, index) => (
<div
key={group.organization.id}
className="bg-white/5 p-3 rounded-lg text-xs"
>
<div className="flex justify-between items-start mb-1">
<span className="text-white font-medium line-clamp-1">
{getOrganizationName(group.organization)}
</span>
<span className="text-purple-300 font-medium">
{formatPrice(group.total)}
</span>
</div>
<div className="text-white/50">
ИНН: {group.organization.inn}
</div>
<div className="text-white/50">
Заявок: {group.items.length}
</div>
</div>
))}
</div>
</div>
)}
<Separator className="bg-white/10" />
{/* Итоговая стоимость */}
<div className="space-y-2">
<div className="flex justify-between">
<span className="text-white/70">Стоимость заявок:</span>
<span className="text-white">{formatPrice(availableTotal)}</span>
</div>
<div className="flex justify-between text-lg font-semibold">
<span className="text-white">Общая сумма:</span>
<span className="text-purple-300">{formatPrice(availableTotal)}</span>
</div>
</div>
<Separator className="bg-white/10" />
{/* Статус заявок */}
<div className="space-y-3">
{canOrder ? (
<div className="flex items-center space-x-2 text-green-400 text-sm">
<CheckCircle className="h-4 w-4" />
<span>Готово к отправке</span>
</div>
) : (
<div className="flex items-center space-x-2 text-orange-400 text-sm">
<AlertTriangle className="h-4 w-4" />
<span>Нет доступных заявок</span>
</div>
)}
{unavailableItems.length > 0 && (
<div className="bg-orange-500/10 border border-orange-500/20 rounded-lg p-3 text-xs">
<div className="text-orange-400 font-medium mb-1">
Внимание!
</div>
<div className="text-orange-300">
{unavailableItems.length} заявок недоступно.
Они будут исключены при отправке.
</div>
</div>
)}
{sellerCount > 1 && (
<div className="bg-blue-500/10 border border-blue-500/20 rounded-lg p-3 text-xs">
<div className="text-blue-400 font-medium mb-1">
Несколько продавцов
</div>
<div className="text-blue-300">
Ваши заявки будут отправлены {sellerCount} разным продавцам
для рассмотрения.
</div>
</div>
)}
</div>
{/* Кнопка отправки заявок */}
<Button
onClick={handleOrder}
disabled={!canOrder || isProcessingOrder}
className={`w-full h-12 text-sm font-medium ${
canOrder
? 'bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white'
: 'bg-gray-500/20 text-gray-400 cursor-not-allowed'
}`}
>
<ShoppingCart className="h-4 w-4 mr-2" />
{isProcessingOrder
? 'Отправляем заявки...'
: canOrder
? `Отправить заявки • ${formatPrice(availableTotal)}`
: 'Невозможно отправить заявки'
}
</Button>
{/* Дополнительная информация */}
<div className="text-xs text-white/50 space-y-1">
<p> Заявки будут отправлены продавцам для рассмотрения</p>
<p> Окончательные условия согласовываются с каждым продавцом</p>
<p> Вы можете изменить количество товаров до отправки заявок</p>
</div>
</div>
</div>
)
}

View File

@ -3,7 +3,6 @@
import { useAuth } from '@/hooks/useAuth'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar'
import { useRouter, usePathname } from 'next/navigation'
import {
@ -11,7 +10,8 @@ import {
LogOut,
Store,
MessageCircle,
Wrench
Wrench,
Warehouse
} from 'lucide-react'
export function Sidebar() {
@ -67,10 +67,15 @@ export function Sidebar() {
router.push('/services')
}
const handleWarehouseClick = () => {
router.push('/warehouse')
}
const isSettingsActive = pathname === '/settings'
const isMarketActive = pathname.startsWith('/market')
const isMessengerActive = pathname.startsWith('/messenger')
const isServicesActive = pathname.startsWith('/services')
const isWarehouseActive = pathname.startsWith('/warehouse')
return (
<div className="fixed left-0 top-0 h-full w-56 bg-white/10 backdrop-blur-xl border-r border-white/20 p-3">
@ -153,6 +158,22 @@ export function Sidebar() {
</Button>
)}
{/* Склад - только для оптовиков */}
{user?.organization?.type === 'WHOLESALE' && (
<Button
variant={isWarehouseActive ? "secondary" : "ghost"}
className={`w-full justify-start text-left transition-all duration-200 h-8 text-xs ${
isWarehouseActive
? 'bg-white/20 text-white hover:bg-white/30'
: 'text-white/80 hover:bg-white/10 hover:text-white'
} cursor-pointer`}
onClick={handleWarehouseClick}
>
<Warehouse className="h-3 w-3 mr-2" />
Склад
</Button>
)}
<Button
variant={isSettingsActive ? "secondary" : "ghost"}
className={`w-full justify-start text-left transition-all duration-200 h-8 text-xs ${

View File

@ -0,0 +1,205 @@
"use client"
import { useQuery } from '@apollo/client'
import { Card } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { GET_CATEGORIES, GET_MY_CART } from '@/graphql/queries'
import { Package2, ArrowRight, Sparkles, ShoppingCart } from 'lucide-react'
interface Category {
id: string
name: string
createdAt: string
updatedAt: string
}
interface MarketCategoriesProps {
onSelectCategory: (categoryId: string, categoryName: string) => void
onShowCart?: () => void
}
export function MarketCategories({ onSelectCategory, onShowCart }: MarketCategoriesProps) {
const { data, loading, error } = useQuery(GET_CATEGORIES)
const { data: cartData } = useQuery(GET_MY_CART)
const categories: Category[] = data?.categories || []
const cart = cartData?.myCart
const uniqueItemsCount = cart?.items?.length || 0
if (loading) {
return (
<div className="h-full flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-16 w-16 border-4 border-white border-t-transparent mx-auto mb-4"></div>
<p className="text-white/70">Загружаем категории...</p>
</div>
</div>
)
}
if (error) {
return (
<div className="h-full flex items-center justify-center">
<div className="text-center">
<Package2 className="h-16 w-16 text-red-400/40 mx-auto mb-4" />
<p className="text-red-400">Ошибка загрузки категорий</p>
<p className="text-white/40 text-sm mt-2">{error.message}</p>
</div>
</div>
)
}
return (
<div className="h-full flex flex-col p-6">
{/* Заголовок */}
<div className="flex items-center justify-between mb-8">
<div className="flex items-center space-x-3">
<div className="p-3 rounded-xl bg-gradient-to-r from-purple-500/20 to-pink-500/20 border border-purple-500/30">
<Package2 className="h-8 w-8 text-purple-400" />
</div>
<div>
<h1 className="text-2xl font-bold text-white mb-1">
Каталог товаров
</h1>
<p className="text-white/60">
Выберите категорию для просмотра товаров от оптовиков
</p>
</div>
</div>
{/* Кнопка корзины */}
{onShowCart && (
<Button
onClick={onShowCart}
className="bg-gradient-to-r from-purple-500/20 to-pink-500/20 hover:from-purple-500/30 hover:to-pink-500/30 text-white border-purple-500/30 hover:border-purple-400/50 transition-all duration-200 shadow-lg px-6 py-3"
>
<ShoppingCart className="h-5 w-5 mr-2" />
Корзина {uniqueItemsCount > 0 && `(${uniqueItemsCount})`}
</Button>
)}
</div>
{/* Категории */}
<div className="flex-1 overflow-auto">
{categories.length === 0 ? (
<div className="glass-card p-8">
<div className="text-center">
<Package2 className="h-16 w-16 text-white/20 mx-auto mb-4" />
<h3 className="text-lg font-semibold text-white mb-2">
Категории отсутствуют
</h3>
<p className="text-white/60">
Пока нет доступных категорий товаров
</p>
</div>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
{/* Карточка "Все товары" */}
<Card
onClick={() => onSelectCategory('', 'Все товары')}
className="group relative overflow-hidden bg-gradient-to-br from-indigo-500/10 via-purple-500/10 to-pink-500/10 backdrop-blur border-white/10 hover:border-white/20 transition-all duration-300 cursor-pointer hover:scale-105"
>
<div className="p-6 h-32 flex flex-col justify-between">
<div className="flex items-center justify-between">
<div className="p-3 rounded-lg bg-gradient-to-r from-indigo-500/20 to-purple-500/20 border border-indigo-500/30">
<Sparkles className="h-6 w-6 text-indigo-400" />
</div>
<ArrowRight className="h-5 w-5 text-white/40 group-hover:text-white/80 transition-colors" />
</div>
<div>
<h3 className="text-lg font-semibold text-white group-hover:text-white transition-colors">
Все товары
</h3>
<p className="text-white/60 text-sm">
Просмотреть весь каталог
</p>
</div>
</div>
{/* Эффект при наведении */}
<div className="absolute inset-0 bg-gradient-to-r from-indigo-500/5 to-purple-500/5 opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
</Card>
{/* Карточки категорий */}
{categories.map((category, index) => {
// Разные градиенты для разных категорий
const gradients = [
'from-purple-500/10 via-pink-500/10 to-red-500/10',
'from-blue-500/10 via-cyan-500/10 to-teal-500/10',
'from-green-500/10 via-emerald-500/10 to-lime-500/10',
'from-yellow-500/10 via-orange-500/10 to-red-500/10',
'from-pink-500/10 via-rose-500/10 to-purple-500/10',
'from-indigo-500/10 via-blue-500/10 to-cyan-500/10',
'from-teal-500/10 via-green-500/10 to-emerald-500/10'
]
const borderColors = [
'border-purple-500/30',
'border-blue-500/30',
'border-green-500/30',
'border-orange-500/30',
'border-pink-500/30',
'border-indigo-500/30',
'border-teal-500/30'
]
const iconColors = [
'text-purple-400',
'text-blue-400',
'text-green-400',
'text-orange-400',
'text-pink-400',
'text-indigo-400',
'text-teal-400'
]
const bgColors = [
'from-purple-500/20 to-pink-500/20',
'from-blue-500/20 to-cyan-500/20',
'from-green-500/20 to-emerald-500/20',
'from-yellow-500/20 to-orange-500/20',
'from-pink-500/20 to-rose-500/20',
'from-indigo-500/20 to-blue-500/20',
'from-teal-500/20 to-green-500/20'
]
const gradient = gradients[index % gradients.length]
const borderColor = borderColors[index % borderColors.length]
const iconColor = iconColors[index % iconColors.length]
const bgColor = bgColors[index % bgColors.length]
return (
<Card
key={category.id}
onClick={() => onSelectCategory(category.id, category.name)}
className={`group relative overflow-hidden bg-gradient-to-br ${gradient} backdrop-blur border-white/10 hover:${borderColor} transition-all duration-300 cursor-pointer hover:scale-105`}
>
<div className="p-6 h-32 flex flex-col justify-between">
<div className="flex items-center justify-between">
<div className={`p-3 rounded-lg bg-gradient-to-r ${bgColor} border ${borderColor}`}>
<Package2 className={`h-6 w-6 ${iconColor}`} />
</div>
<ArrowRight className="h-5 w-5 text-white/40 group-hover:text-white/80 transition-colors" />
</div>
<div>
<h3 className="text-lg font-semibold text-white group-hover:text-white transition-colors">
{category.name}
</h3>
<p className="text-white/60 text-sm">
Товары категории
</p>
</div>
</div>
{/* Эффект при наведении */}
<div className={`absolute inset-0 bg-gradient-to-r ${gradient} opacity-0 group-hover:opacity-50 transition-opacity duration-300`} />
</Card>
)
})}
</div>
)}
</div>
</div>
)
}

View File

@ -1,5 +1,6 @@
"use client"
import { useState } from 'react'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Card } from '@/components/ui/card'
import { Sidebar } from '@/components/dashboard/sidebar'
@ -8,8 +9,29 @@ import { MarketFulfillment } from './market-fulfillment'
import { MarketSellers } from './market-sellers'
import { MarketLogistics } from './market-logistics'
import { MarketWholesale } from './market-wholesale'
import { MarketProducts } from './market-products'
import { MarketCategories } from './market-categories'
import { MarketRequests } from './market-requests'
export function MarketDashboard() {
const [productsView, setProductsView] = useState<'categories' | 'products' | 'cart'>('categories')
const [selectedCategory, setSelectedCategory] = useState<{ id: string; name: string } | null>(null)
const handleSelectCategory = (categoryId: string, categoryName: string) => {
setSelectedCategory({ id: categoryId, name: categoryName })
setProductsView('products')
}
const handleBackToCategories = () => {
setProductsView('categories')
setSelectedCategory(null)
}
const handleShowCart = () => {
setProductsView('cart')
setSelectedCategory(null)
}
return (
<div className="h-screen bg-gradient-smooth flex overflow-hidden">
<Sidebar />
@ -17,8 +39,18 @@ export function MarketDashboard() {
<div className="h-full w-full flex flex-col">
{/* Основной контент с табами */}
<div className="flex-1 overflow-hidden">
<Tabs defaultValue="counterparties" className="h-full flex flex-col">
<TabsList className="grid w-full grid-cols-5 bg-white/5 backdrop-blur border-white/10 flex-shrink-0">
<Tabs
defaultValue="counterparties"
className="h-full flex flex-col"
onValueChange={(value) => {
if (value === 'products') {
// Сбрасываем состояние когда переходим на вкладку товаров
setProductsView('categories')
setSelectedCategory(null)
}
}}
>
<TabsList className="grid w-full grid-cols-6 bg-white/5 backdrop-blur border-white/10 flex-shrink-0">
<TabsTrigger
value="counterparties"
className="data-[state=active]:bg-white/20 data-[state=active]:text-white text-white/70"
@ -49,6 +81,12 @@ export function MarketDashboard() {
>
Оптовик
</TabsTrigger>
<TabsTrigger
value="products"
className="data-[state=active]:bg-white/20 data-[state=active]:text-white text-white/70"
>
Товары
</TabsTrigger>
</TabsList>
<TabsContent value="counterparties" className="flex-1 overflow-hidden mt-6">
@ -80,6 +118,22 @@ export function MarketDashboard() {
<MarketWholesale />
</Card>
</TabsContent>
<TabsContent value="products" className="flex-1 overflow-hidden mt-6">
<Card className="glass-card h-full overflow-hidden p-0">
{productsView === 'categories' ? (
<MarketCategories onSelectCategory={handleSelectCategory} onShowCart={handleShowCart} />
) : productsView === 'products' ? (
<MarketProducts
selectedCategoryId={selectedCategory?.id}
selectedCategoryName={selectedCategory?.name}
onBackToCategories={handleBackToCategories}
/>
) : (
<MarketRequests />
)}
</Card>
</TabsContent>
</Tabs>
</div>
</div>

View File

@ -0,0 +1,243 @@
"use client"
import { useState, useMemo } from 'react'
import { useQuery } from '@apollo/client'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Search, ShoppingBag, Package2, ArrowLeft } from 'lucide-react'
import { ProductCard } from './product-card'
import { GET_ALL_PRODUCTS } from '@/graphql/queries'
interface Product {
id: string
name: string
article: string
description?: string
price: number
quantity: number
category?: { id: string; name: string }
brand?: string
color?: string
size?: string
weight?: number
dimensions?: string
material?: string
images: string[]
mainImage?: string
isActive: boolean
createdAt: string
organization: {
id: string
inn: string
name?: string
fullName?: string
type: string
address?: string
phones?: Array<{ value: string }>
emails?: Array<{ value: string }>
users?: Array<{ id: string, avatar?: string, managerName?: string }>
}
}
interface MarketProductsProps {
selectedCategoryId?: string
selectedCategoryName?: string
onBackToCategories?: () => void
}
export function MarketProducts({ selectedCategoryId, selectedCategoryName, onBackToCategories }: MarketProductsProps) {
const [searchTerm, setSearchTerm] = useState('')
const [selectedCategory, setSelectedCategory] = useState<string>('')
const [localSearch, setLocalSearch] = useState('')
const { data, loading, refetch } = useQuery(GET_ALL_PRODUCTS, {
variables: {
search: searchTerm || null,
category: selectedCategoryId || selectedCategory || null
}
})
const products: Product[] = data?.allProducts || []
// Получаем уникальные категории из товаров
const categories = useMemo(() => {
const allCategories = products
.map(product => product.category?.name)
.filter(Boolean)
.filter((category, index, arr) => arr.indexOf(category) === index)
.sort()
return allCategories
}, [products])
const handleSearch = () => {
setSearchTerm(localSearch.trim())
}
// Фильтруем товары по доступности
const availableProducts = products.filter(product => product.isActive && product.quantity > 0)
const totalProducts = products.length
const availableCount = availableProducts.length
return (
<div className="h-full flex flex-col space-y-4 overflow-hidden p-6">
{/* Кнопка назад и заголовок */}
{selectedCategoryName && onBackToCategories && (
<div className="flex items-center space-x-3 flex-shrink-0">
<Button
onClick={onBackToCategories}
variant="outline"
className="glass-secondary text-white hover:text-white border-white/20 hover:border-white/40"
>
<ArrowLeft className="h-4 w-4 mr-2" />
Назад к категориям
</Button>
<div>
<h2 className="text-xl font-bold text-white">{selectedCategoryName}</h2>
<p className="text-white/60 text-sm">Товары выбранной категории</p>
</div>
</div>
)}
{/* Поиск */}
<div className="flex space-x-4 flex-shrink-0">
<div className="relative flex-1">
<Search className="absolute left-3 top-3 h-4 w-4 text-white/40" />
<Input
placeholder="Поиск товаров по названию, артикулу, бренду..."
value={localSearch}
onChange={(e) => setLocalSearch(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
className="pl-10 glass-input text-white placeholder:text-white/40 h-10"
/>
</div>
<Button
onClick={handleSearch}
className="bg-purple-500/20 hover:bg-purple-500/30 text-purple-300 border-purple-500/30 cursor-pointer h-10"
>
<Search className="h-4 w-4 mr-2" />
Найти
</Button>
</div>
{/* Категории */}
<div className="flex-shrink-0">
<h4 className="text-white font-medium mb-3 flex items-center">
<Package2 className="h-4 w-4 mr-2" />
Категории
</h4>
<div className="flex flex-wrap gap-2">
<Button
onClick={() => setSelectedCategory('')}
variant={selectedCategory === '' ? 'default' : 'outline'}
className={`h-8 px-3 text-sm transition-all ${
selectedCategory === ''
? 'bg-purple-500 hover:bg-purple-600 text-white'
: 'bg-white/5 hover:bg-white/10 text-white/70 border-white/20'
}`}
>
Все категории
</Button>
{categories.map((category) => (
<Button
key={category}
onClick={() => setSelectedCategory(category!)}
variant={selectedCategory === category ? 'default' : 'outline'}
className={`h-8 px-3 text-sm transition-all ${
selectedCategory === category
? 'bg-purple-500 hover:bg-purple-600 text-white'
: 'bg-white/5 hover:bg-white/10 text-white/70 border-white/20'
}`}
>
{category}
</Button>
))}
</div>
</div>
{/* Заголовок с статистикой */}
<div className="flex items-center justify-between flex-shrink-0">
<div className="flex items-center space-x-3">
<ShoppingBag className="h-6 w-6 text-purple-400" />
<div>
<h3 className="text-lg font-semibold text-white">Товары оптовиков</h3>
<p className="text-white/60 text-sm">
Найдено {totalProducts} товаров, доступно {availableCount}
</p>
</div>
</div>
{/* Активные фильтры */}
<div className="flex items-center space-x-2">
{searchTerm && (
<div className="bg-purple-500/20 px-3 py-1 rounded-full text-purple-300 text-sm flex items-center">
<Search className="h-3 w-3 mr-1" />
{searchTerm}
<button
onClick={() => {
setSearchTerm('')
setLocalSearch('')
}}
className="ml-2 hover:text-white"
>
×
</button>
</div>
)}
{selectedCategory && (
<div className="bg-purple-500/20 px-3 py-1 rounded-full text-purple-300 text-sm flex items-center">
<Package2 className="h-3 w-3 mr-1" />
{selectedCategory}
<button
onClick={() => setSelectedCategory('')}
className="ml-2 hover:text-white"
>
×
</button>
</div>
)}
</div>
</div>
{/* Список товаров */}
<div className="flex-1 overflow-auto min-h-0">
{loading ? (
<div className="flex items-center justify-center p-8">
<div className="text-white/60">Загружаем товары...</div>
</div>
) : products.length === 0 ? (
<div className="glass-card p-8">
<div className="text-center">
<ShoppingBag className="h-12 w-12 text-white/20 mx-auto mb-4" />
<p className="text-white/60">
{searchTerm || selectedCategory ? 'Товары не найдены' : 'Пока нет товаров для отображения'}
</p>
<p className="text-white/40 text-sm mt-2">
{searchTerm || selectedCategory
? 'Попробуйте изменить условия поиска или фильтры'
: 'Оптовики еще не добавили свои товары'
}
</p>
</div>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4">
{products.map((product) => (
<ProductCard
key={product.id}
product={product}
/>
))}
</div>
)}
</div>
{/* Пагинация будет добавлена позже если понадобится */}
</div>
)
}

View File

@ -0,0 +1,84 @@
"use client"
import { useQuery } from '@apollo/client'
import { CartItems } from '../cart/cart-items'
import { CartSummary } from '../cart/cart-summary'
import { GET_MY_CART } from '@/graphql/queries'
import { ShoppingCart, Package } from 'lucide-react'
export function MarketRequests() {
const { data, loading, error } = useQuery(GET_MY_CART)
const cart = data?.myCart
const hasItems = cart?.items && cart.items.length > 0
if (loading) {
return (
<div className="h-full flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-16 w-16 border-4 border-white border-t-transparent mx-auto mb-4"></div>
<p className="text-white/70">Загружаем заявки...</p>
</div>
</div>
)
}
if (error) {
return (
<div className="h-full flex items-center justify-center">
<div className="text-center">
<ShoppingCart className="h-16 w-16 text-red-400/40 mx-auto mb-4" />
<p className="text-red-400">Ошибка загрузки заявок</p>
<p className="text-white/40 text-sm mt-2">{error.message}</p>
</div>
</div>
)
}
return (
<div className="h-full w-full flex flex-col">
{/* Заголовок */}
<div className="flex items-center space-x-3 p-6 border-b border-white/10">
<ShoppingCart className="h-6 w-6 text-purple-400" />
<div>
<h1 className="text-xl font-bold text-white">Мои заявки</h1>
<p className="text-white/60">
{hasItems
? `${cart.totalItems} заявок на сумму ${new Intl.NumberFormat('ru-RU', { style: 'currency', currency: 'RUB' }).format(cart.totalPrice)}`
: 'У вас пока нет заявок'
}
</p>
</div>
</div>
{/* Основной контент */}
<div className="flex-1 overflow-hidden">
{hasItems ? (
<div className="h-full grid grid-cols-1 lg:grid-cols-3 gap-6 p-6">
{/* Заявки */}
<div className="lg:col-span-2">
<div className="glass-card h-full overflow-hidden">
<CartItems cart={cart} />
</div>
</div>
{/* Сводка заявок */}
<div className="lg:col-span-1">
<div className="glass-card h-fit">
<CartSummary cart={cart} />
</div>
</div>
</div>
) : (
<div className="h-full flex flex-col items-center justify-center text-center p-8">
<Package className="h-24 w-24 text-white/20 mb-6" />
<h2 className="text-xl font-semibold text-white mb-2">Нет заявок</h2>
<p className="text-white/60 mb-6 max-w-md">
Добавьте товары в заявки из раздела &quot;Товары&quot;, чтобы создать заявку для оптовика
</p>
</div>
)}
</div>
</div>
)
}

View File

@ -0,0 +1,292 @@
"use client"
import { useState } from 'react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import {
ShoppingCart,
Eye,
ChevronLeft,
ChevronRight
} from 'lucide-react'
import { OrganizationAvatar } from './organization-avatar'
import { Input } from '@/components/ui/input'
import Image from 'next/image'
import { useMutation } from '@apollo/client'
import { ADD_TO_CART } from '@/graphql/mutations'
import { GET_MY_CART } from '@/graphql/queries'
import { toast } from 'sonner'
interface Product {
id: string
name: string
article: string
description?: string
price: number
quantity: number
category?: { id: string; name: string }
brand?: string
color?: string
size?: string
weight?: number
dimensions?: string
material?: string
images: string[]
mainImage?: string
isActive: boolean
createdAt: string
organization: {
id: string
inn: string
name?: string
fullName?: string
type: string
address?: string
phones?: Array<{ value: string }>
emails?: Array<{ value: string }>
users?: Array<{ id: string, avatar?: string, managerName?: string }>
}
}
interface ProductCardProps {
product: Product
}
export function ProductCard({ product }: ProductCardProps) {
const [currentImageIndex, setCurrentImageIndex] = useState(0)
const [isImageDialogOpen, setIsImageDialogOpen] = useState(false)
const [quantity, setQuantity] = useState(1)
const [addToCart, { loading: addingToCart }] = useMutation(ADD_TO_CART, {
refetchQueries: [{ query: GET_MY_CART }],
onCompleted: (data) => {
if (data.addToCart.success) {
toast.success(data.addToCart.message)
setQuantity(1) // Сбрасываем количество после добавления
} else {
toast.error(data.addToCart.message)
}
},
onError: (error) => {
toast.error('Ошибка при добавлении в заявки')
console.error('Error adding to cart:', error)
}
})
const displayPrice = new Intl.NumberFormat('ru-RU', {
style: 'currency',
currency: 'RUB'
}).format(product.price)
const displayName = product.organization.name || product.organization.fullName || 'Неизвестная организация'
const images = product.images.length > 0 ? product.images : [product.mainImage].filter(Boolean)
const hasMultipleImages = images.length > 1
const handleAddToCart = async () => {
try {
await addToCart({
variables: {
productId: product.id,
quantity: quantity
}
})
} catch (error) {
console.error('Error adding to cart:', error)
}
}
const nextImage = () => {
setCurrentImageIndex((prev) => (prev + 1) % images.length)
}
const prevImage = () => {
setCurrentImageIndex((prev) => (prev - 1 + images.length) % images.length)
}
const getStockStatus = () => {
if (product.quantity === 0) return { text: 'Нет в наличии', color: 'bg-red-500/20 text-red-300' }
if (product.quantity < 10) return { text: 'Мало', color: 'bg-orange-500/20 text-orange-300' }
return { text: 'В наличии', color: 'bg-green-500/20 text-green-300' }
}
const stockStatus = getStockStatus()
const canAddToCart = product.quantity > 0 && product.isActive
return (
<div className="glass-card p-3 hover:bg-white/10 transition-all duration-300 group">
{/* Изображения товара */}
<div className="relative mb-3 aspect-video bg-white/5 rounded-lg overflow-hidden">
{images.length > 0 ? (
<>
<Image
src={images[currentImageIndex] || '/placeholder-product.png'}
alt={product.name}
fill
className="object-cover cursor-pointer"
onClick={() => setIsImageDialogOpen(true)}
/>
{/* Навигация по изображениям */}
{hasMultipleImages && (
<>
<button
onClick={prevImage}
className="absolute left-2 top-1/2 -translate-y-1/2 bg-black/50 hover:bg-black/70 text-white p-1 rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
>
<ChevronLeft className="h-4 w-4" />
</button>
<button
onClick={nextImage}
className="absolute right-2 top-1/2 -translate-y-1/2 bg-black/50 hover:bg-black/70 text-white p-1 rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
>
<ChevronRight className="h-4 w-4" />
</button>
{/* Индикаторы изображений */}
<div className="absolute bottom-2 left-1/2 -translate-x-1/2 flex space-x-1">
{images.map((_, index) => (
<div
key={index}
className={`w-2 h-2 rounded-full transition-all ${
index === currentImageIndex ? 'bg-white' : 'bg-white/50'
}`}
/>
))}
</div>
</>
)}
{/* Кнопка увеличения */}
<button
onClick={() => setIsImageDialogOpen(true)}
className="absolute top-2 right-2 bg-black/50 hover:bg-black/70 text-white p-1 rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
>
<Eye className="h-4 w-4" />
</button>
</>
) : (
<div className="absolute inset-0 flex items-center justify-center">
<ShoppingCart className="h-8 w-8 text-white/20" />
</div>
)}
</div>
{/* Информация о товаре */}
<div className="space-y-2">
{/* Название и цена */}
<div>
<h3 className="font-semibold text-white text-sm mb-1 line-clamp-1">{product.name}</h3>
<div className="flex items-center justify-between">
<span className="text-base font-bold text-purple-300">{displayPrice}</span>
<Badge className={`${stockStatus.color} text-xs`}>
{stockStatus.text}
</Badge>
</div>
</div>
{/* Краткая информация */}
<div className="flex items-center justify-between text-xs text-white/60">
<span>Арт: {product.article}</span>
{product.category && (
<span className="bg-white/10 px-2 py-1 rounded text-xs">{product.category.name}</span>
)}
</div>
{/* Информация о продавце */}
<div className="border-t border-white/10 pt-2">
<div className="flex items-center space-x-2">
<OrganizationAvatar organization={product.organization} size="sm" />
<div className="flex-1 min-w-0">
<p className="font-medium text-white text-xs truncate">{displayName}</p>
<p className="text-xs text-white/50">ИНН: {product.organization.inn}</p>
</div>
</div>
</div>
{/* Выбор количества и добавление в заявки */}
{canAddToCart ? (
<div className="space-y-2">
{/* Выбор количества */}
<div className="flex items-center justify-between">
<span className="text-xs text-white/70">Количество:</span>
<Input
type="number"
min="1"
max={product.quantity}
value={quantity}
onChange={(e) => {
const value = parseInt(e.target.value) || 1
if (value >= 1 && value <= product.quantity) {
setQuantity(value)
}
}}
className="w-16 h-6 text-xs text-center glass-input text-white border-white/20"
/>
</div>
{/* Кнопка добавления в заявки */}
<Button
onClick={handleAddToCart}
disabled={addingToCart}
className="w-full h-8 bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white border-0 text-xs"
>
<ShoppingCart className="h-3 w-3 mr-1" />
{addingToCart ? 'Добавление...' : 'В заявки'}
</Button>
</div>
) : (
<Button
disabled
className="w-full h-8 bg-gray-500/20 text-gray-400 border-0 text-xs cursor-not-allowed"
>
<ShoppingCart className="h-3 w-3 mr-1" />
Недоступно
</Button>
)}
</div>
{/* Диалог просмотра изображений */}
<Dialog open={isImageDialogOpen} onOpenChange={setIsImageDialogOpen}>
<DialogContent className="max-w-4xl max-h-[90vh] bg-black/90 backdrop-blur-xl border border-white/20 p-0">
<DialogHeader className="sr-only">
<DialogTitle>Просмотр изображения товара {product.name}</DialogTitle>
</DialogHeader>
<div className="relative">
{images.length > 0 && (
<div className="relative aspect-square">
<Image
src={images[currentImageIndex] || '/placeholder-product.png'}
alt={product.name}
fill
className="object-contain"
/>
{hasMultipleImages && (
<>
<button
onClick={prevImage}
className="absolute left-4 top-1/2 -translate-y-1/2 bg-black/50 hover:bg-black/70 text-white p-3 rounded-full"
>
<ChevronLeft className="h-6 w-6" />
</button>
<button
onClick={nextImage}
className="absolute right-4 top-1/2 -translate-y-1/2 bg-black/50 hover:bg-black/70 text-white p-3 rounded-full"
>
<ChevronRight className="h-6 w-6" />
</button>
</>
)}
<div className="absolute bottom-4 left-1/2 -translate-x-1/2 bg-black/50 px-3 py-1 rounded-full text-white text-sm">
{currentImageIndex + 1} из {images.length}
</div>
</div>
)}
</div>
</DialogContent>
</Dialog>
</div>
)
}

View File

@ -0,0 +1,219 @@
"use client"
import { useState } from 'react'
import { useMutation } from '@apollo/client'
import { Card } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog'
import { DELETE_PRODUCT } from '@/graphql/mutations'
import { Edit3, Trash2, Package, Eye, EyeOff } from 'lucide-react'
import { toast } from 'sonner'
interface Product {
id: string
name: string
article: string
description: string
price: number
quantity: number
category: { id: string; name: string } | null
brand: string
color: string
size: string
weight: number
dimensions: string
material: string
images: string[]
mainImage: string
isActive: boolean
createdAt: string
updatedAt: string
}
interface ProductCardProps {
product: Product
onEdit: (product: Product) => void
onDeleted: () => void
}
export function ProductCard({ product, onEdit, onDeleted }: ProductCardProps) {
const [deleteProduct, { loading: deleting }] = useMutation(DELETE_PRODUCT)
const handleDelete = async () => {
try {
await deleteProduct({
variables: { id: product.id }
})
toast.success('Товар успешно удален')
onDeleted()
} catch (error) {
console.error('Error deleting product:', error)
toast.error('Ошибка при удалении товара')
}
}
const formatPrice = (price: number) => {
return new Intl.NumberFormat('ru-RU', {
style: 'currency',
currency: 'RUB',
minimumFractionDigits: 0
}).format(price)
}
const getStatusColor = () => {
if (!product.isActive) return 'bg-gray-500/20 text-gray-300 border-gray-400/30'
if (product.quantity === 0) return 'bg-red-500/20 text-red-300 border-red-400/30'
if (product.quantity < 10) return 'bg-yellow-500/20 text-yellow-300 border-yellow-400/30'
return 'bg-green-500/20 text-green-300 border-green-400/30'
}
const getStatusText = () => {
if (!product.isActive) return 'Неактивен'
if (product.quantity === 0) return 'Нет в наличии'
if (product.quantity < 10) return 'Мало на складе'
return 'В наличии'
}
return (
<Card className="glass-card group relative overflow-hidden transition-all duration-300 hover:scale-[1.02] hover:shadow-xl hover:shadow-purple-500/20">
{/* Изображение товара */}
<div className="relative h-48 bg-white/5 overflow-hidden">
{product.mainImage || product.images[0] ? (
<img
src={product.mainImage || product.images[0]}
alt={product.name}
className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-110"
/>
) : (
<div className="w-full h-full flex items-center justify-center">
<Package className="h-16 w-16 text-white/30" />
</div>
)}
{/* Статус товара */}
<div className="absolute top-2 left-2">
<Badge className={`text-xs px-2 py-1 ${getStatusColor()}`}>
{getStatusText()}
</Badge>
</div>
{/* Индикатор активности */}
<div className="absolute top-2 right-2">
{product.isActive ? (
<Eye className="h-4 w-4 text-green-300" />
) : (
<EyeOff className="h-4 w-4 text-gray-400" />
)}
</div>
{/* Кнопки управления */}
<div className="absolute bottom-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity flex gap-1">
<Button
size="sm"
variant="outline"
onClick={() => onEdit(product)}
className="p-1 h-7 w-7 bg-white/20 border-white/30 hover:bg-white/30 backdrop-blur"
>
<Edit3 className="h-3 w-3 text-white" />
</Button>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
size="sm"
variant="outline"
className="p-1 h-7 w-7 bg-red-500/20 border-red-400/30 hover:bg-red-500/30 backdrop-blur"
>
<Trash2 className="h-3 w-3 text-white" />
</Button>
</AlertDialogTrigger>
<AlertDialogContent className="glass-card border-white/10">
<AlertDialogHeader>
<AlertDialogTitle className="text-white">Удалить товар?</AlertDialogTitle>
<AlertDialogDescription className="text-white/70">
Вы уверены, что хотите удалить товар &quot;{product.name}&quot;?
Это действие нельзя отменить.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel className="glass-secondary text-white hover:text-white">
Отмена
</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
disabled={deleting}
className="bg-red-600 hover:bg-red-700 text-white"
>
{deleting ? 'Удаление...' : 'Удалить'}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</div>
{/* Информация о товаре */}
<div className="p-4 space-y-3">
{/* Название и артикул */}
<div>
<h3 className="text-white font-medium text-sm line-clamp-2 leading-tight">
{product.name}
</h3>
<p className="text-white/60 text-xs mt-1">
Арт. {product.article}
</p>
</div>
{/* Цена и количество */}
<div className="flex items-center justify-between">
<div className="text-white font-semibold">
{formatPrice(product.price)}
</div>
<div className="text-white/70 text-sm">
{product.quantity} шт.
</div>
</div>
{/* Дополнительная информация */}
<div className="space-y-1">
{product.category && (
<div className="flex items-center gap-2">
<Badge variant="outline" className="glass-secondary text-white/60 border-white/20 text-xs">
{product.category.name}
</Badge>
</div>
)}
<div className="flex flex-wrap gap-1">
{product.brand && (
<span className="text-white/50 text-xs bg-white/10 px-2 py-1 rounded">
{product.brand}
</span>
)}
{product.color && (
<span className="text-white/50 text-xs bg-white/10 px-2 py-1 rounded">
{product.color}
</span>
)}
{product.size && (
<span className="text-white/50 text-xs bg-white/10 px-2 py-1 rounded">
{product.size}
</span>
)}
</div>
</div>
{/* Описание (если есть) */}
{product.description && (
<p className="text-white/60 text-xs line-clamp-2 leading-relaxed">
{product.description}
</p>
)}
</div>
{/* Эффект градиента при наведении */}
<div className="absolute inset-0 bg-gradient-to-t from-purple-600/0 via-transparent to-transparent opacity-0 group-hover:opacity-20 transition-opacity duration-300 pointer-events-none" />
</Card>
)
}

View File

@ -0,0 +1,487 @@
"use client"
import { useState, useRef } from 'react'
import { useMutation, useQuery } from '@apollo/client'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Card } from '@/components/ui/card'
import { CREATE_PRODUCT, UPDATE_PRODUCT } from '@/graphql/mutations'
import { GET_CATEGORIES } from '@/graphql/queries'
import { Upload, X, Star, Plus, Image as ImageIcon } from 'lucide-react'
import { toast } from 'sonner'
interface Product {
id: string
name: string
article: string
description: string
price: number
quantity: number
category: { id: string; name: string } | null
brand: string
color: string
size: string
weight: number
dimensions: string
material: string
images: string[]
mainImage: string
isActive: boolean
}
interface ProductFormProps {
product?: Product | null
onSave: () => void
onCancel: () => void
}
export function ProductForm({ product, onSave, onCancel }: ProductFormProps) {
const [formData, setFormData] = useState({
name: product?.name || '',
article: product?.article || '',
description: product?.description || '',
price: product?.price || 0,
quantity: product?.quantity || 0,
categoryId: product?.category?.id || 'none',
brand: product?.brand || '',
color: product?.color || '',
size: product?.size || '',
weight: product?.weight || 0,
dimensions: product?.dimensions || '',
material: product?.material || '',
images: product?.images || [],
mainImage: product?.mainImage || '',
isActive: product?.isActive ?? true
})
const [isUploading, setIsUploading] = useState(false)
const [uploadingImages, setUploadingImages] = useState<Set<number>>(new Set())
const fileInputRef = useRef<HTMLInputElement>(null)
const [createProduct, { loading: creating }] = useMutation(CREATE_PRODUCT)
const [updateProduct, { loading: updating }] = useMutation(UPDATE_PRODUCT)
// Загружаем категории
const { data: categoriesData } = useQuery(GET_CATEGORIES)
const loading = creating || updating
const handleInputChange = (field: string, value: string | number | boolean) => {
setFormData(prev => ({
...prev,
[field]: value
}))
}
const handleImageUpload = async (files: FileList) => {
const newUploadingIndexes = new Set<number>()
const startIndex = formData.images.length
// Добавляем плейсхолдеры для загружаемых изображений
const placeholders = Array.from(files).map((_, index) => {
newUploadingIndexes.add(startIndex + index)
return '' // Пустой URL как плейсхолдер
})
setUploadingImages(prev => new Set([...prev, ...newUploadingIndexes]))
setFormData(prev => ({
...prev,
images: [...prev.images, ...placeholders]
}))
try {
// Загружаем каждое изображение
const uploadPromises = Array.from(files).map(async (file, index) => {
const actualIndex = startIndex + index
const formData = new FormData()
formData.append('file', file)
formData.append('type', 'product')
const response = await fetch('/api/upload-file', {
method: 'POST',
body: formData
})
if (!response.ok) {
throw new Error('Ошибка загрузки изображения')
}
const result = await response.json()
return { index: actualIndex, url: result.fileUrl }
})
const results = await Promise.all(uploadPromises)
// Обновляем URLs загруженных изображений
setFormData(prev => {
const newImages = [...prev.images]
results.forEach(({ index, url }) => {
newImages[index] = url
})
return {
...prev,
images: newImages,
mainImage: prev.mainImage || results[0]?.url || '' // Устанавливаем первое изображение как главное
}
})
toast.success('Изображения успешно загружены')
} catch (error) {
console.error('Error uploading images:', error)
toast.error('Ошибка загрузки изображений')
// Удаляем неудачные плейсхолдеры
setFormData(prev => ({
...prev,
images: prev.images.slice(0, startIndex)
}))
} finally {
// Убираем индикаторы загрузки
setUploadingImages(prev => {
const updated = new Set(prev)
newUploadingIndexes.forEach(index => updated.delete(index))
return updated
})
}
}
const handleRemoveImage = (indexToRemove: number) => {
setFormData(prev => {
const newImages = prev.images.filter((_, index) => index !== indexToRemove)
const removedImageUrl = prev.images[indexToRemove]
return {
...prev,
images: newImages,
mainImage: prev.mainImage === removedImageUrl ? (newImages[0] || '') : prev.mainImage
}
})
}
const handleSetMainImage = (imageUrl: string) => {
setFormData(prev => ({
...prev,
mainImage: imageUrl
}))
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!formData.name || !formData.article || formData.price <= 0) {
toast.error('Пожалуйста, заполните все обязательные поля')
return
}
try {
const input = {
name: formData.name,
article: formData.article,
description: formData.description || undefined,
price: formData.price,
quantity: formData.quantity,
categoryId: formData.categoryId && formData.categoryId !== 'none' ? formData.categoryId : undefined,
brand: formData.brand || undefined,
color: formData.color || undefined,
size: formData.size || undefined,
weight: formData.weight || undefined,
dimensions: formData.dimensions || undefined,
material: formData.material || undefined,
images: formData.images.filter(img => img), // Убираем пустые строки
mainImage: formData.mainImage || undefined,
isActive: formData.isActive
}
if (product) {
await updateProduct({
variables: { id: product.id, input }
})
toast.success('Товар успешно обновлен')
} else {
await createProduct({
variables: { input }
})
toast.success('Товар успешно создан')
}
onSave()
} catch (error: unknown) {
console.error('Error saving product:', error)
toast.error((error as Error).message || 'Ошибка при сохранении товара')
}
}
return (
<form onSubmit={handleSubmit} className="space-y-6">
{/* Основная информация */}
<Card className="bg-white/5 backdrop-blur border-white/10 p-4">
<h3 className="text-white font-medium mb-4">Основная информация</h3>
<div className="grid grid-cols-2 gap-4">
<div>
<Label className="text-white/80 text-sm mb-2 block">
Название товара <span className="text-red-400">*</span>
</Label>
<Input
value={formData.name}
onChange={(e) => handleInputChange('name', e.target.value)}
placeholder="iPhone 15 Pro Max"
className="glass-input text-white placeholder:text-white/40 h-10"
required
/>
</div>
<div>
<Label className="text-white/80 text-sm mb-2 block">
Артикул <span className="text-red-400">*</span>
</Label>
<Input
value={formData.article}
onChange={(e) => handleInputChange('article', e.target.value)}
placeholder="IP15PM-256-BLU"
className="glass-input text-white placeholder:text-white/40 h-10"
required
/>
</div>
</div>
<div className="mt-4">
<Label className="text-white/80 text-sm mb-2 block">Описание</Label>
<textarea
value={formData.description}
onChange={(e) => handleInputChange('description', e.target.value)}
placeholder="Подробное описание товара..."
className="glass-input text-white placeholder:text-white/40 w-full resize-none"
rows={3}
/>
</div>
<div className="grid grid-cols-2 gap-4 mt-4">
<div>
<Label className="text-white/80 text-sm mb-2 block">
Цена () <span className="text-red-400">*</span>
</Label>
<Input
type="number"
step="0.01"
min="0"
value={formData.price || ''}
onChange={(e) => handleInputChange('price', parseFloat(e.target.value) || 0)}
placeholder="99999.99"
className="glass-input text-white placeholder:text-white/40 h-10"
required
/>
</div>
<div>
<Label className="text-white/80 text-sm mb-2 block">Количество</Label>
<Input
type="number"
min="0"
value={formData.quantity || ''}
onChange={(e) => handleInputChange('quantity', parseInt(e.target.value) || 0)}
placeholder="100"
className="glass-input text-white placeholder:text-white/40 h-10"
/>
</div>
</div>
</Card>
{/* Категоризация */}
<Card className="bg-white/5 backdrop-blur border-white/10 p-4">
<h3 className="text-white font-medium mb-4">Категоризация</h3>
<div className="grid grid-cols-2 gap-4">
<div>
<Label className="text-white/80 text-sm mb-2 block">Категория</Label>
<Select
value={formData.categoryId}
onValueChange={(value) => handleInputChange('categoryId', value)}
>
<SelectTrigger className="glass-input text-white h-10">
<SelectValue placeholder="Выберите категорию" />
</SelectTrigger>
<SelectContent className="glass-card">
<SelectItem value="none">Без категории</SelectItem>
{categoriesData?.categories?.map((category: { id: string; name: string }) => (
<SelectItem key={category.id} value={category.id} className="text-white">
{category.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label className="text-white/80 text-sm mb-2 block">Бренд</Label>
<Input
value={formData.brand}
onChange={(e) => handleInputChange('brand', e.target.value)}
placeholder="Apple"
className="glass-input text-white placeholder:text-white/40 h-10"
/>
</div>
</div>
</Card>
{/* Характеристики */}
<Card className="bg-white/5 backdrop-blur border-white/10 p-4">
<h3 className="text-white font-medium mb-4">Характеристики</h3>
<div className="grid grid-cols-2 gap-4">
<div>
<Label className="text-white/80 text-sm mb-2 block">Цвет</Label>
<Input
value={formData.color}
onChange={(e) => handleInputChange('color', e.target.value)}
placeholder="Синий"
className="glass-input text-white placeholder:text-white/40 h-10"
/>
</div>
<div>
<Label className="text-white/80 text-sm mb-2 block">Размер</Label>
<Input
value={formData.size}
onChange={(e) => handleInputChange('size', e.target.value)}
placeholder="L, XL, 42"
className="glass-input text-white placeholder:text-white/40 h-10"
/>
</div>
<div>
<Label className="text-white/80 text-sm mb-2 block">Вес (кг)</Label>
<Input
type="number"
step="0.001"
min="0"
value={formData.weight || ''}
onChange={(e) => handleInputChange('weight', parseFloat(e.target.value) || 0)}
placeholder="0.221"
className="glass-input text-white placeholder:text-white/40 h-10"
/>
</div>
<div>
<Label className="text-white/80 text-sm mb-2 block">Габариты</Label>
<Input
value={formData.dimensions}
onChange={(e) => handleInputChange('dimensions', e.target.value)}
placeholder="159.9 × 76.7 × 8.25 мм"
className="glass-input text-white placeholder:text-white/40 h-10"
/>
</div>
</div>
<div className="mt-4">
<Label className="text-white/80 text-sm mb-2 block">Материал</Label>
<Input
value={formData.material}
onChange={(e) => handleInputChange('material', e.target.value)}
placeholder="Титан, стекло"
className="glass-input text-white placeholder:text-white/40 h-10"
/>
</div>
</Card>
{/* Изображения */}
<Card className="bg-white/5 backdrop-blur border-white/10 p-4">
<h3 className="text-white font-medium mb-4">Изображения товара</h3>
{/* Кнопка загрузки */}
<div className="mb-4">
<input
ref={fileInputRef}
type="file"
accept="image/*"
multiple
onChange={(e) => e.target.files && handleImageUpload(e.target.files)}
className="hidden"
/>
<Button
type="button"
variant="outline"
onClick={() => fileInputRef.current?.click()}
disabled={isUploading}
className="glass-secondary text-white hover:text-white cursor-pointer"
>
<Upload className="h-4 w-4 mr-2" />
{isUploading ? 'Загрузка...' : 'Добавить изображения'}
</Button>
</div>
{/* Галерея изображений */}
{formData.images.length > 0 && (
<div className="grid grid-cols-3 gap-4">
{formData.images.map((imageUrl, index) => (
<div key={index} className="relative group">
{uploadingImages.has(index) ? (
<div className="aspect-square bg-white/10 rounded-lg flex items-center justify-center">
<div className="animate-spin rounded-full h-8 w-8 border-2 border-white border-t-transparent"></div>
</div>
) : (
<>
<img
src={imageUrl}
alt={`Товар ${index + 1}`}
className="w-full aspect-square object-cover rounded-lg"
/>
{/* Индикатор главного изображения */}
{formData.mainImage === imageUrl && (
<div className="absolute top-2 left-2">
<Star className="h-5 w-5 text-yellow-400 fill-current" />
</div>
)}
{/* Кнопки управления */}
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity flex gap-1">
{formData.mainImage !== imageUrl && (
<Button
type="button"
size="sm"
variant="outline"
onClick={() => handleSetMainImage(imageUrl)}
className="p-1 h-7 w-7 bg-white/20 border-white/30 hover:bg-white/30"
>
<Star className="h-3 w-3 text-white" />
</Button>
)}
<Button
type="button"
size="sm"
variant="outline"
onClick={() => handleRemoveImage(index)}
className="p-1 h-7 w-7 bg-red-500/20 border-red-400/30 hover:bg-red-500/30"
>
<X className="h-3 w-3 text-white" />
</Button>
</div>
</>
)}
</div>
))}
</div>
)}
</Card>
{/* Кнопки управления */}
<div className="flex gap-3 pt-4">
<Button
type="button"
variant="outline"
onClick={onCancel}
className="flex-1 border-purple-400/30 text-purple-200 hover:bg-purple-500/10 hover:border-purple-300 transition-all duration-300"
>
Отмена
</Button>
<Button
type="submit"
disabled={loading || isUploading}
className="flex-1 bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-500 hover:to-pink-500 text-white border-0 shadow-lg shadow-purple-500/25 hover:shadow-purple-500/40 transition-all duration-300"
>
{loading ? 'Сохранение...' : (product ? 'Сохранить изменения' : 'Создать товар')}
</Button>
</div>
</form>
)
}

View File

@ -0,0 +1,207 @@
"use client"
import { useState } from 'react'
import { useQuery } from '@apollo/client'
import { Card } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Sidebar } from '@/components/dashboard/sidebar'
import { ProductForm } from './product-form'
import { ProductCard } from './product-card'
import { GET_MY_PRODUCTS } from '@/graphql/queries'
import { Plus, Search, Package } from 'lucide-react'
import { Input } from '@/components/ui/input'
interface Product {
id: string
name: string
article: string
description: string
price: number
quantity: number
category: { id: string; name: string } | null
brand: string
color: string
size: string
weight: number
dimensions: string
material: string
images: string[]
mainImage: string
isActive: boolean
createdAt: string
updatedAt: string
}
export function WarehouseDashboard() {
const [isDialogOpen, setIsDialogOpen] = useState(false)
const [editingProduct, setEditingProduct] = useState<Product | null>(null)
const [searchQuery, setSearchQuery] = useState('')
const { data, loading, error, refetch } = useQuery(GET_MY_PRODUCTS, {
errorPolicy: 'all'
})
const products: Product[] = data?.myProducts || []
// Фильтрация товаров по поисковому запросу
const filteredProducts = products.filter(product =>
product.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
product.article.toLowerCase().includes(searchQuery.toLowerCase()) ||
product.category?.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
product.brand?.toLowerCase().includes(searchQuery.toLowerCase())
)
const handleCreateProduct = () => {
setEditingProduct(null)
setIsDialogOpen(true)
}
const handleEditProduct = (product: Product) => {
setEditingProduct(product)
setIsDialogOpen(true)
}
const handleProductSaved = () => {
setIsDialogOpen(false)
setEditingProduct(null)
refetch()
}
const handleProductDeleted = () => {
refetch()
}
if (error) {
return (
<div className="h-screen bg-gradient-smooth flex overflow-hidden">
<Sidebar />
<main className="flex-1 ml-56 px-6 py-4 overflow-hidden">
<div className="h-full w-full flex flex-col">
<Card className="flex-1 bg-white/5 backdrop-blur border-white/10 p-6">
<div className="flex items-center justify-center h-full">
<div className="text-center">
<Package className="h-16 w-16 text-white/40 mx-auto mb-4" />
<h3 className="text-lg font-medium text-white mb-2">Ошибка загрузки</h3>
<p className="text-white/60 text-sm mb-4">
{error.message || 'Не удалось загрузить товары'}
</p>
<Button
onClick={() => refetch()}
className="bg-purple-600 hover:bg-purple-700 text-white"
>
Попробовать снова
</Button>
</div>
</div>
</Card>
</div>
</main>
</div>
)
}
return (
<div className="h-screen bg-gradient-smooth flex overflow-hidden">
<Sidebar />
<main className="flex-1 ml-56 px-6 py-4 overflow-hidden">
<div className="h-full w-full flex flex-col">
{/* Заголовок и поиск */}
<div className="flex items-center justify-between mb-4 flex-shrink-0">
<div>
<h1 className="text-xl font-bold text-white mb-1">Склад товаров</h1>
<p className="text-white/70 text-sm">Управление ассортиментом вашего склада</p>
</div>
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
<DialogTrigger asChild>
<Button
onClick={handleCreateProduct}
className="bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 text-white border-0 shadow-lg shadow-purple-500/25 transition-all duration-300"
>
<Plus className="w-4 h-4 mr-2" />
Добавить товар
</Button>
</DialogTrigger>
<DialogContent className="glass-card max-w-4xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="text-white">
{editingProduct ? 'Редактировать товар' : 'Добавить новый товар'}
</DialogTitle>
</DialogHeader>
<ProductForm
product={editingProduct}
onSave={handleProductSaved}
onCancel={() => setIsDialogOpen(false)}
/>
</DialogContent>
</Dialog>
</div>
{/* Поиск */}
<div className="mb-4 flex-shrink-0">
<div className="relative max-w-md">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-white/50" />
<Input
type="text"
placeholder="Поиск по названию, артикулу, категории..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="glass-input text-white placeholder:text-white/50 pl-10 h-10"
/>
</div>
</div>
{/* Основной контент */}
<Card className="flex-1 bg-white/5 backdrop-blur border-white/10 p-6 overflow-hidden">
{loading ? (
<div className="flex items-center justify-center h-full">
<div className="text-center">
<div className="animate-spin rounded-full h-16 w-16 border-4 border-white border-t-transparent mx-auto mb-4"></div>
<p className="text-white/70">Загрузка товаров...</p>
</div>
</div>
) : filteredProducts.length === 0 ? (
<div className="flex items-center justify-center h-full">
<div className="text-center">
<Package className="h-16 w-16 text-white/40 mx-auto mb-4" />
<h3 className="text-lg font-medium text-white mb-2">
{searchQuery ? 'Товары не найдены' : 'Склад пуст'}
</h3>
<p className="text-white/60 text-sm mb-4">
{searchQuery
? 'Попробуйте изменить критерии поиска'
: 'Добавьте ваш первый товар на склад'
}
</p>
{!searchQuery && (
<Button
onClick={handleCreateProduct}
className="bg-purple-600 hover:bg-purple-700 text-white"
>
<Plus className="w-4 h-4 mr-2" />
Добавить товар
</Button>
)}
</div>
</div>
) : (
<div className="h-full overflow-y-auto">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
{filteredProducts.map((product) => (
<ProductCard
key={product.id}
product={product}
onEdit={handleEditProduct}
onDeleted={handleProductDeleted}
/>
))}
</div>
</div>
)}
</Card>
</div>
</main>
</div>
)
}

View File

@ -635,3 +635,186 @@ export const DELETE_SUPPLY = gql`
deleteSupply(id: $id)
}
`
// Мутации для товаров оптовика
export const CREATE_PRODUCT = gql`
mutation CreateProduct($input: ProductInput!) {
createProduct(input: $input) {
success
message
product {
id
name
article
description
price
quantity
category {
id
name
}
brand
color
size
weight
dimensions
material
images
mainImage
isActive
createdAt
updatedAt
}
}
}
`
export const UPDATE_PRODUCT = gql`
mutation UpdateProduct($id: ID!, $input: ProductInput!) {
updateProduct(id: $id, input: $input) {
success
message
product {
id
name
article
description
price
quantity
category {
id
name
}
brand
color
size
weight
dimensions
material
images
mainImage
isActive
createdAt
updatedAt
}
}
}
`
export const DELETE_PRODUCT = gql`
mutation DeleteProduct($id: ID!) {
deleteProduct(id: $id)
}
`
// Мутации для корзины
export const ADD_TO_CART = gql`
mutation AddToCart($productId: ID!, $quantity: Int = 1) {
addToCart(productId: $productId, quantity: $quantity) {
success
message
cart {
id
totalPrice
totalItems
items {
id
quantity
totalPrice
isAvailable
availableQuantity
product {
id
name
article
price
quantity
images
mainImage
organization {
id
name
fullName
}
}
}
}
}
}
`
export const UPDATE_CART_ITEM = gql`
mutation UpdateCartItem($productId: ID!, $quantity: Int!) {
updateCartItem(productId: $productId, quantity: $quantity) {
success
message
cart {
id
totalPrice
totalItems
items {
id
quantity
totalPrice
isAvailable
availableQuantity
product {
id
name
article
price
quantity
images
mainImage
organization {
id
name
fullName
}
}
}
}
}
}
`
export const REMOVE_FROM_CART = gql`
mutation RemoveFromCart($productId: ID!) {
removeFromCart(productId: $productId) {
success
message
cart {
id
totalPrice
totalItems
items {
id
quantity
totalPrice
isAvailable
availableQuantity
product {
id
name
article
price
quantity
images
mainImage
organization {
id
name
fullName
}
}
}
}
}
}
`
export const CLEAR_CART = gql`
mutation ClearCart {
clearCart
}
`

View File

@ -77,6 +77,34 @@ export const GET_MY_SUPPLIES = gql`
}
`
export const GET_MY_PRODUCTS = gql`
query GetMyProducts {
myProducts {
id
name
article
description
price
quantity
category {
id
name
}
brand
color
size
weight
dimensions
material
images
mainImage
isActive
createdAt
updatedAt
}
}
`
// Запросы для контрагентов
export const SEARCH_ORGANIZATIONS = gql`
query SearchOrganizations($type: OrganizationType, $search: String) {
@ -301,3 +329,111 @@ export const GET_CONVERSATIONS = gql`
}
}
`
export const GET_CATEGORIES = gql`
query GetCategories {
categories {
id
name
createdAt
updatedAt
}
}
`
export const GET_ALL_PRODUCTS = gql`
query GetAllProducts($search: String, $category: String) {
allProducts(search: $search, category: $category) {
id
name
article
description
price
quantity
category {
id
name
}
brand
color
size
weight
dimensions
material
images
mainImage
isActive
createdAt
updatedAt
organization {
id
inn
name
fullName
type
address
phones
emails
users {
id
avatar
managerName
}
}
}
}
`
export const GET_MY_CART = gql`
query GetMyCart {
myCart {
id
totalPrice
totalItems
items {
id
quantity
totalPrice
isAvailable
availableQuantity
createdAt
updatedAt
product {
id
name
article
description
price
quantity
brand
color
size
images
mainImage
isActive
category {
id
name
}
organization {
id
inn
name
fullName
type
address
phones
emails
users {
id
avatar
managerName
}
}
}
}
createdAt
updatedAt
}
}
`

View File

@ -483,6 +483,161 @@ export const resolvers = {
include: { organization: true },
orderBy: { createdAt: 'desc' }
})
},
// Мои товары (для оптовиков)
myProducts: async (_: unknown, __: unknown, context: Context) => {
if (!context.user) {
throw new GraphQLError('Требуется авторизация', {
extensions: { code: 'UNAUTHENTICATED' }
})
}
const currentUser = await prisma.user.findUnique({
where: { id: context.user.id },
include: { organization: true }
})
if (!currentUser?.organization) {
throw new GraphQLError('У пользователя нет организации')
}
// Проверяем, что это оптовик
if (currentUser.organization.type !== 'WHOLESALE') {
throw new GraphQLError('Товары доступны только для оптовиков')
}
return await prisma.product.findMany({
where: { organizationId: currentUser.organization.id },
include: {
category: true,
organization: true
},
orderBy: { createdAt: 'desc' }
})
},
// Все товары всех оптовиков для маркета
allProducts: async (_: unknown, args: { search?: string; category?: string }, context: Context) => {
if (!context.user) {
throw new GraphQLError('Требуется авторизация', {
extensions: { code: 'UNAUTHENTICATED' }
})
}
const where: Record<string, unknown> = {
isActive: true, // Показываем только активные товары
organization: {
type: 'WHOLESALE' // Только товары оптовиков
}
}
if (args.search) {
where.OR = [
{ name: { contains: args.search, mode: 'insensitive' } },
{ article: { contains: args.search, mode: 'insensitive' } },
{ description: { contains: args.search, mode: 'insensitive' } },
{ brand: { contains: args.search, mode: 'insensitive' } }
]
}
if (args.category) {
where.categoryId = args.category
}
return await prisma.product.findMany({
where,
include: {
category: true,
organization: {
include: {
users: true
}
}
},
orderBy: { createdAt: 'desc' },
take: 100 // Ограничиваем количество результатов
})
},
// Все категории
categories: async (_: unknown, __: unknown, context: Context) => {
if (!context.user) {
throw new GraphQLError('Требуется авторизация', {
extensions: { code: 'UNAUTHENTICATED' }
})
}
return await prisma.category.findMany({
orderBy: { name: 'asc' }
})
},
// Корзина пользователя
myCart: async (_: unknown, __: unknown, context: Context) => {
if (!context.user) {
throw new GraphQLError('Требуется авторизация', {
extensions: { code: 'UNAUTHENTICATED' }
})
}
const currentUser = await prisma.user.findUnique({
where: { id: context.user.id },
include: { organization: true }
})
if (!currentUser?.organization) {
throw new GraphQLError('У пользователя нет организации')
}
// Найти или создать корзину для организации
let cart = await prisma.cart.findUnique({
where: { organizationId: currentUser.organization.id },
include: {
items: {
include: {
product: {
include: {
category: true,
organization: {
include: {
users: true
}
}
}
}
}
},
organization: true
}
})
if (!cart) {
cart = await prisma.cart.create({
data: {
organizationId: currentUser.organization.id
},
include: {
items: {
include: {
product: {
include: {
category: true,
organization: {
include: {
users: true
}
}
}
}
}
},
organization: true
}
})
}
return cart
}
},
@ -592,7 +747,7 @@ export const resolvers = {
registerFulfillmentOrganization: async (
_: unknown,
args: { input: { phone: string; inn: string } },
args: { input: { phone: string; inn: string; type: 'FULFILLMENT' | 'LOGIST' | 'WHOLESALE' } },
context: Context
) => {
if (!context.user) {
@ -601,7 +756,7 @@ export const resolvers = {
})
}
const { inn } = args.input
const { inn, type } = args.input
// Валидируем ИНН
if (!dadataService.validateInn(inn)) {
@ -675,7 +830,7 @@ export const resolvers = {
revenue: organizationData.revenue,
taxSystem: organizationData.taxSystem,
type: 'FULFILLMENT',
type: type,
dadataData: JSON.parse(JSON.stringify(organizationData.rawData))
}
})
@ -695,7 +850,7 @@ export const resolvers = {
return {
success: true,
message: 'Фулфилмент организация успешно зарегистрирована',
message: 'Организация успешно зарегистрирована',
user: updatedUser
}
@ -2096,6 +2251,599 @@ export const resolvers = {
console.error('Error deleting supply:', error)
return false
}
},
// Создать товар
createProduct: async (_: unknown, args: {
input: {
name: string;
article: string;
description?: string;
price: number;
quantity: number;
categoryId?: string;
brand?: string;
color?: string;
size?: string;
weight?: number;
dimensions?: string;
material?: string;
images?: string[];
mainImage?: string;
isActive?: boolean;
}
}, context: Context) => {
if (!context.user) {
throw new GraphQLError('Требуется авторизация', {
extensions: { code: 'UNAUTHENTICATED' }
})
}
const currentUser = await prisma.user.findUnique({
where: { id: context.user.id },
include: { organization: true }
})
if (!currentUser?.organization) {
throw new GraphQLError('У пользователя нет организации')
}
// Проверяем, что это оптовик
if (currentUser.organization.type !== 'WHOLESALE') {
throw new GraphQLError('Товары доступны только для оптовиков')
}
// Проверяем уникальность артикула в рамках организации
const existingProduct = await prisma.product.findFirst({
where: {
article: args.input.article,
organizationId: currentUser.organization.id
}
})
if (existingProduct) {
return {
success: false,
message: 'Товар с таким артикулом уже существует'
}
}
try {
const product = await prisma.product.create({
data: {
name: args.input.name,
article: args.input.article,
description: args.input.description,
price: args.input.price,
quantity: args.input.quantity,
categoryId: args.input.categoryId,
brand: args.input.brand,
color: args.input.color,
size: args.input.size,
weight: args.input.weight,
dimensions: args.input.dimensions,
material: args.input.material,
images: args.input.images || [],
mainImage: args.input.mainImage,
isActive: args.input.isActive ?? true,
organizationId: currentUser.organization.id
},
include: {
category: true,
organization: true
}
})
return {
success: true,
message: 'Товар успешно создан',
product
}
} catch (error) {
console.error('Error creating product:', error)
return {
success: false,
message: 'Ошибка при создании товара'
}
}
},
// Обновить товар
updateProduct: async (_: unknown, args: {
id: string;
input: {
name: string;
article: string;
description?: string;
price: number;
quantity: number;
categoryId?: string;
brand?: string;
color?: string;
size?: string;
weight?: number;
dimensions?: string;
material?: string;
images?: string[];
mainImage?: string;
isActive?: boolean;
}
}, context: Context) => {
if (!context.user) {
throw new GraphQLError('Требуется авторизация', {
extensions: { code: 'UNAUTHENTICATED' }
})
}
const currentUser = await prisma.user.findUnique({
where: { id: context.user.id },
include: { organization: true }
})
if (!currentUser?.organization) {
throw new GraphQLError('У пользователя нет организации')
}
// Проверяем, что товар принадлежит текущей организации
const existingProduct = await prisma.product.findFirst({
where: {
id: args.id,
organizationId: currentUser.organization.id
}
})
if (!existingProduct) {
throw new GraphQLError('Товар не найден или нет доступа')
}
// Проверяем уникальность артикула (если он изменился)
if (args.input.article !== existingProduct.article) {
const duplicateProduct = await prisma.product.findFirst({
where: {
article: args.input.article,
organizationId: currentUser.organization.id,
NOT: { id: args.id }
}
})
if (duplicateProduct) {
return {
success: false,
message: 'Товар с таким артикулом уже существует'
}
}
}
try {
const product = await prisma.product.update({
where: { id: args.id },
data: {
name: args.input.name,
article: args.input.article,
description: args.input.description,
price: args.input.price,
quantity: args.input.quantity,
categoryId: args.input.categoryId,
brand: args.input.brand,
color: args.input.color,
size: args.input.size,
weight: args.input.weight,
dimensions: args.input.dimensions,
material: args.input.material,
images: args.input.images || [],
mainImage: args.input.mainImage,
isActive: args.input.isActive ?? true
},
include: {
category: true,
organization: true
}
})
return {
success: true,
message: 'Товар успешно обновлен',
product
}
} catch (error) {
console.error('Error updating product:', error)
return {
success: false,
message: 'Ошибка при обновлении товара'
}
}
},
// Удалить товар
deleteProduct: async (_: unknown, args: { id: string }, context: Context) => {
if (!context.user) {
throw new GraphQLError('Требуется авторизация', {
extensions: { code: 'UNAUTHENTICATED' }
})
}
const currentUser = await prisma.user.findUnique({
where: { id: context.user.id },
include: { organization: true }
})
if (!currentUser?.organization) {
throw new GraphQLError('У пользователя нет организации')
}
// Проверяем, что товар принадлежит текущей организации
const existingProduct = await prisma.product.findFirst({
where: {
id: args.id,
organizationId: currentUser.organization.id
}
})
if (!existingProduct) {
throw new GraphQLError('Товар не найден или нет доступа')
}
try {
await prisma.product.delete({
where: { id: args.id }
})
return true
} catch (error) {
console.error('Error deleting product:', error)
return false
}
},
// Добавить товар в корзину
addToCart: async (_: unknown, args: { productId: string; quantity: number }, context: Context) => {
if (!context.user) {
throw new GraphQLError('Требуется авторизация', {
extensions: { code: 'UNAUTHENTICATED' }
})
}
const currentUser = await prisma.user.findUnique({
where: { id: context.user.id },
include: { organization: true }
})
if (!currentUser?.organization) {
throw new GraphQLError('У пользователя нет организации')
}
// Проверяем, что товар существует и активен
const product = await prisma.product.findFirst({
where: {
id: args.productId,
isActive: true
},
include: {
organization: true
}
})
if (!product) {
return {
success: false,
message: 'Товар не найден или неактивен'
}
}
// Проверяем, что пользователь не пытается добавить свой собственный товар
if (product.organizationId === currentUser.organization.id) {
return {
success: false,
message: 'Нельзя добавлять собственные товары в корзину'
}
}
// Найти или создать корзину
let cart = await prisma.cart.findUnique({
where: { organizationId: currentUser.organization.id }
})
if (!cart) {
cart = await prisma.cart.create({
data: {
organizationId: currentUser.organization.id
}
})
}
try {
// Проверяем, есть ли уже такой товар в корзине
const existingCartItem = await prisma.cartItem.findUnique({
where: {
cartId_productId: {
cartId: cart.id,
productId: args.productId
}
}
})
if (existingCartItem) {
// Обновляем количество
const newQuantity = existingCartItem.quantity + args.quantity
if (newQuantity > product.quantity) {
return {
success: false,
message: `Недостаточно товара в наличии. Доступно: ${product.quantity}`
}
}
await prisma.cartItem.update({
where: { id: existingCartItem.id },
data: { quantity: newQuantity }
})
} else {
// Создаем новый элемент корзины
if (args.quantity > product.quantity) {
return {
success: false,
message: `Недостаточно товара в наличии. Доступно: ${product.quantity}`
}
}
await prisma.cartItem.create({
data: {
cartId: cart.id,
productId: args.productId,
quantity: args.quantity
}
})
}
// Возвращаем обновленную корзину
const updatedCart = await prisma.cart.findUnique({
where: { id: cart.id },
include: {
items: {
include: {
product: {
include: {
category: true,
organization: {
include: {
users: true
}
}
}
}
}
},
organization: true
}
})
return {
success: true,
message: 'Товар добавлен в корзину',
cart: updatedCart
}
} catch (error) {
console.error('Error adding to cart:', error)
return {
success: false,
message: 'Ошибка при добавлении в корзину'
}
}
},
// Обновить количество товара в корзине
updateCartItem: async (_: unknown, args: { productId: string; quantity: number }, context: Context) => {
if (!context.user) {
throw new GraphQLError('Требуется авторизация', {
extensions: { code: 'UNAUTHENTICATED' }
})
}
const currentUser = await prisma.user.findUnique({
where: { id: context.user.id },
include: { organization: true }
})
if (!currentUser?.organization) {
throw new GraphQLError('У пользователя нет организации')
}
const cart = await prisma.cart.findUnique({
where: { organizationId: currentUser.organization.id }
})
if (!cart) {
return {
success: false,
message: 'Корзина не найдена'
}
}
// Проверяем, что товар существует в корзине
const cartItem = await prisma.cartItem.findUnique({
where: {
cartId_productId: {
cartId: cart.id,
productId: args.productId
}
},
include: {
product: true
}
})
if (!cartItem) {
return {
success: false,
message: 'Товар не найден в корзине'
}
}
if (args.quantity <= 0) {
return {
success: false,
message: 'Количество должно быть больше 0'
}
}
if (args.quantity > cartItem.product.quantity) {
return {
success: false,
message: `Недостаточно товара в наличии. Доступно: ${cartItem.product.quantity}`
}
}
try {
await prisma.cartItem.update({
where: { id: cartItem.id },
data: { quantity: args.quantity }
})
// Возвращаем обновленную корзину
const updatedCart = await prisma.cart.findUnique({
where: { id: cart.id },
include: {
items: {
include: {
product: {
include: {
category: true,
organization: {
include: {
users: true
}
}
}
}
}
},
organization: true
}
})
return {
success: true,
message: 'Количество товара обновлено',
cart: updatedCart
}
} catch (error) {
console.error('Error updating cart item:', error)
return {
success: false,
message: 'Ошибка при обновлении корзины'
}
}
},
// Удалить товар из корзины
removeFromCart: async (_: unknown, args: { productId: string }, context: Context) => {
if (!context.user) {
throw new GraphQLError('Требуется авторизация', {
extensions: { code: 'UNAUTHENTICATED' }
})
}
const currentUser = await prisma.user.findUnique({
where: { id: context.user.id },
include: { organization: true }
})
if (!currentUser?.organization) {
throw new GraphQLError('У пользователя нет организации')
}
const cart = await prisma.cart.findUnique({
where: { organizationId: currentUser.organization.id }
})
if (!cart) {
return {
success: false,
message: 'Корзина не найдена'
}
}
try {
await prisma.cartItem.delete({
where: {
cartId_productId: {
cartId: cart.id,
productId: args.productId
}
}
})
// Возвращаем обновленную корзину
const updatedCart = await prisma.cart.findUnique({
where: { id: cart.id },
include: {
items: {
include: {
product: {
include: {
category: true,
organization: {
include: {
users: true
}
}
}
}
}
},
organization: true
}
})
return {
success: true,
message: 'Товар удален из корзины',
cart: updatedCart
}
} catch (error) {
console.error('Error removing from cart:', error)
return {
success: false,
message: 'Ошибка при удалении из корзины'
}
}
},
// Очистить корзину
clearCart: async (_: unknown, __: unknown, context: Context) => {
if (!context.user) {
throw new GraphQLError('Требуется авторизация', {
extensions: { code: 'UNAUTHENTICATED' }
})
}
const currentUser = await prisma.user.findUnique({
where: { id: context.user.id },
include: { organization: true }
})
if (!currentUser?.organization) {
throw new GraphQLError('У пользователя нет организации')
}
const cart = await prisma.cart.findUnique({
where: { organizationId: currentUser.organization.id }
})
if (!cart) {
return false
}
try {
await prisma.cartItem.deleteMany({
where: { cartId: cart.id }
})
return true
} catch (error) {
console.error('Error clearing cart:', error)
return false
}
}
},
@ -2114,6 +2862,29 @@ export const resolvers = {
}
},
Cart: {
totalPrice: (parent: { items: Array<{ product: { price: number }, quantity: number }> }) => {
return parent.items.reduce((total, item) => {
return total + (Number(item.product.price) * item.quantity)
}, 0)
},
totalItems: (parent: { items: Array<{ quantity: number }> }) => {
return parent.items.reduce((total, item) => total + item.quantity, 0)
}
},
CartItem: {
totalPrice: (parent: { product: { price: number }, quantity: number }) => {
return Number(parent.product.price) * parent.quantity
},
isAvailable: (parent: { product: { quantity: number, isActive: boolean }, quantity: number }) => {
return parent.product.isActive && parent.product.quantity >= parent.quantity
},
availableQuantity: (parent: { product: { quantity: number } }) => {
return parent.product.quantity
}
},
User: {
organization: async (parent: { organizationId?: string; organization?: unknown }) => {
// Если организация уже загружена через include, возвращаем её

View File

@ -28,6 +28,18 @@ export const typeDefs = gql`
# Расходники организации
mySupplies: [Supply!]!
# Товары оптовика
myProducts: [Product!]!
# Все товары всех оптовиков для маркета
allProducts(search: String, category: String): [Product!]!
# Все категории
categories: [Category!]!
# Корзина пользователя
myCart: Cart
}
type Mutation {
@ -77,6 +89,17 @@ export const typeDefs = gql`
createSupply(input: SupplyInput!): SupplyResponse!
updateSupply(id: ID!, input: SupplyInput!): SupplyResponse!
deleteSupply(id: ID!): Boolean!
# Работа с товарами (для оптовиков)
createProduct(input: ProductInput!): ProductResponse!
updateProduct(id: ID!, input: ProductInput!): ProductResponse!
deleteProduct(id: ID!): Boolean!
# Работа с корзиной
addToCart(productId: ID!, quantity: Int = 1): CartResponse!
updateCartItem(productId: ID!, quantity: Int!): CartResponse!
removeFromCart(productId: ID!): CartResponse!
clearCart: Boolean!
}
# Типы данных
@ -160,6 +183,7 @@ export const typeDefs = gql`
input FulfillmentRegistrationInput {
phone: String!
inn: String!
type: OrganizationType!
}
input SellerRegistrationInput {
@ -349,6 +373,89 @@ export const typeDefs = gql`
supply: Supply
}
# Типы для категорий товаров
type Category {
id: ID!
name: String!
createdAt: String!
updatedAt: String!
}
# Типы для товаров оптовика
type Product {
id: ID!
name: String!
article: String!
description: String
price: Float!
quantity: Int!
category: Category
brand: String
color: String
size: String
weight: Float
dimensions: String
material: String
images: [String!]!
mainImage: String
isActive: Boolean!
createdAt: String!
updatedAt: String!
organization: Organization!
}
input ProductInput {
name: String!
article: String!
description: String
price: Float!
quantity: Int!
categoryId: ID
brand: String
color: String
size: String
weight: Float
dimensions: String
material: String
images: [String!]
mainImage: String
isActive: Boolean
}
type ProductResponse {
success: Boolean!
message: String!
product: Product
}
# Типы для корзины
type Cart {
id: ID!
items: [CartItem!]!
totalPrice: Float!
totalItems: Int!
createdAt: String!
updatedAt: String!
organization: Organization!
}
type CartItem {
id: ID!
product: Product!
quantity: Int!
totalPrice: Float!
isAvailable: Boolean!
availableQuantity: Int!
createdAt: String!
updatedAt: String!
}
type CartResponse {
success: Boolean!
message: String!
cart: Cart
}
# JSON скаляр
scalar JSON
`

View File

@ -64,7 +64,7 @@ interface UseAuthReturn {
}>
// Регистрация организаций
registerFulfillmentOrganization: (phone: string, inn: string) => Promise<{
registerFulfillmentOrganization: (phone: string, inn: string, type: 'FULFILLMENT' | 'LOGIST' | 'WHOLESALE') => Promise<{
success: boolean
message: string
user?: User
@ -254,7 +254,7 @@ export const useAuth = (): UseAuthReturn => {
}
}
const registerFulfillmentOrganization = async (phone: string, inn: string) => {
const registerFulfillmentOrganization = async (phone: string, inn: string, type: 'FULFILLMENT' | 'LOGIST' | 'WHOLESALE') => {
try {
setIsLoading(true)
@ -264,7 +264,7 @@ export const useAuth = (): UseAuthReturn => {
const { data } = await registerFulfillmentMutation({
variables: {
input: { phone, inn }
input: { phone, inn, type }
}
})