const { PrismaClient } = require('@prisma/client') const prisma = new PrismaClient() async function testResolverLogic() { console.log('🧪 Тестируем логику резолвера fulfillmentReceiveOrder...') try { // Найдем организацию фулфилмента const fulfillmentOrg = await prisma.organization.findFirst({ where: { type: 'FULFILLMENT' }, select: { id: true, name: true } }) if (!fulfillmentOrg) { console.log('❌ Организация фулфилмента не найдена') return } // Найдем заказ поставки в статусе SHIPPED const testOrder = await prisma.supplyOrder.findFirst({ where: { fulfillmentCenterId: fulfillmentOrg.id, status: 'SHIPPED', }, include: { items: { include: { product: { include: { category: true, }, }, }, }, organization: true, partner: true, }, }) if (!testOrder) { console.log('❌ Не найден заказ поставки в статусе SHIPPED') return } console.log(`📋 Найден заказ: ${testOrder.id}`) console.log(` Тип расходников: ${testOrder.consumableType}`) console.log(` Элементов в заказе: ${testOrder.items.length}`) // Имитируем логику резолвера для каждого элемента for (const item of testOrder.items) { console.log(`\n📦 Обрабатываем товар: ${item.product.name}`) console.log(` Артикул: "${item.product.article}"`) console.log(` Количество: ${item.quantity}`) // Проверяем, есть ли артикул if (!item.product.article || item.product.article.trim() === '') { console.log(' ❌ ПРОБЛЕМА: У товара нет артикула!') continue } // Определяем тип расходника (как в оригинальном коде) const isSellerSupply = testOrder.consumableType === 'SELLER_CONSUMABLES' const targetOrganizationId = fulfillmentOrg.id console.log(` Тип поставки: ${isSellerSupply ? 'SELLER_CONSUMABLES' : 'FULFILLMENT_CONSUMABLES'}`) // Формируем условие поиска (как в исправленном коде) const whereCondition = isSellerSupply ? { organizationId: targetOrganizationId, article: item.product.article, // ИСПРАВЛЕННАЯ ЛОГИКА type: 'SELLER_CONSUMABLES', sellerOwnerId: testOrder.organizationId, } : { organizationId: targetOrganizationId, article: item.product.article, // ИСПРАВЛЕННАЯ ЛОГИКА type: 'FULFILLMENT_CONSUMABLES', sellerOwnerId: null, } console.log(' 🔍 Условие поиска существующего Supply:') console.log(' ', JSON.stringify(whereCondition, null, 6)) // Ищем существующий Supply const existingSupply = await prisma.supply.findFirst({ where: whereCondition, }) if (existingSupply) { console.log(` ✅ НАЙДЕН существующий Supply:`) console.log(` ID: ${existingSupply.id}`) console.log(` Название: ${existingSupply.name}`) console.log(` Текущий остаток: ${existingSupply.currentStock}`) console.log(` 📈 ОБНОВИЛИ БЫ: ${existingSupply.currentStock} + ${item.quantity} = ${existingSupply.currentStock + item.quantity}`) } else { console.log(` 🆕 НЕ найден существующий Supply - СОЗДАЛИ БЫ НОВЫЙ`) console.log(` Название: ${item.product.name}`) console.log(` Артикул: ${item.product.article}`) console.log(` Количество: ${item.quantity}`) console.log(` Тип: ${isSellerSupply ? 'SELLER_CONSUMABLES' : 'FULFILLMENT_CONSUMABLES'}`) } } console.log('\n🎯 ПРОВЕРЬТЕ:') console.log('1. Все товары имеют артикулы?') console.log('2. Логика поиска корректна?') console.log('3. Создаются ли новые Supply или обновляются существующие?') } catch (error) { console.error('❌ Ошибка при тестировании резолвера:', error) console.error('Детали ошибки:', error.message) if (error.stack) { console.error('Stack trace:', error.stack) } } finally { await prisma.$disconnect() } } testResolverLogic()