import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() async function testApiKeySave() { try { console.log('🔍 ТЕСТ СОХРАНЕНИЯ API КЛЮЧА') // Найдем организацию Rennel const org = await prisma.organization.findFirst({ where: { name: 'Rennel', type: 'SELLER' }, include: { apiKeys: { where: { marketplace: 'WILDBERRIES' }, orderBy: { createdAt: 'desc' }, }, }, }) if (!org) { console.log('❌ Организация Rennel не найдена') return } console.log('\n📊 СОСТОЯНИЕ ДО ТЕСТА:') console.log('- Организация:', org.name) console.log('- Всего WB ключей:', org.apiKeys.length) if (org.apiKeys.length > 0) { const currentKey = org.apiKeys[0] console.log('- Текущий ключ ID:', currentKey.id) console.log('- Длина:', currentKey.apiKey?.length) console.log('- Тип:', currentKey.apiKey?.startsWith('eyJ') ? 'JWT' : 'Тестовый') } // Тестовый валидный JWT ключ (более короткий для теста) const testJwtKey = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL2FjY291bnQud2lsZGJlcnJpZXMucnUiLCJzdWIiOjEyMzQ1Njc4OTAsImV4cCI6MTcyNjY3MjgwMCwidXNlclR5cGUiOiJzZWxsZXIiLCJzY29wZSI6WyJhZHZlcnRpc2luZyIsInN0YXRpc3RpY3MiLCJvcmRlcnMiXX0.test_signature_here' console.log('\n🔄 ИМИТАЦИЯ ОБНОВЛЕНИЯ КЛЮЧА...') // Имитируем обновление через API (как делает мутация) const existingKey = await prisma.apiKey.findUnique({ where: { organizationId_marketplace: { organizationId: org.id, marketplace: 'WILDBERRIES', }, }, }) if (existingKey) { console.log('- Найден существующий ключ:', existingKey.id) // Обновляем как в мутации const updated = await prisma.apiKey.update({ where: { organizationId_marketplace: { organizationId: org.id, marketplace: 'WILDBERRIES', }, }, data: { apiKey: testJwtKey, isActive: true, validationData: { validatedAt: new Date().toISOString() }, }, }) console.log('✅ Ключ обновлен:', updated.id) console.log('- Новая длина:', updated.apiKey?.length) console.log('- Новый тип:', updated.apiKey?.startsWith('eyJ') ? 'JWT' : 'Тестовый') } else { console.log('- Существующий ключ не найден, создаем новый') const created = await prisma.apiKey.create({ data: { organizationId: org.id, marketplace: 'WILDBERRIES', apiKey: testJwtKey, isActive: true, validationData: { validatedAt: new Date().toISOString() }, }, }) console.log('✅ Новый ключ создан:', created.id) } // Проверим результат console.log('\n📊 СОСТОЯНИЕ ПОСЛЕ ТЕСТА:') const updatedOrg = await prisma.organization.findFirst({ where: { name: 'Rennel', type: 'SELLER' }, include: { apiKeys: { where: { marketplace: 'WILDBERRIES' }, orderBy: { createdAt: 'desc' }, }, }, }) if (updatedOrg && updatedOrg.apiKeys.length > 0) { const newKey = updatedOrg.apiKeys[0] console.log('- Ключ ID:', newKey.id) console.log('- Длина:', newKey.apiKey?.length) console.log('- Тип:', newKey.apiKey?.startsWith('eyJ') ? 'JWT' : 'Тестовый') console.log('- Активен:', newKey.isActive) console.log('- Обновлен:', newKey.updatedAt.toISOString()) } console.log('\n🎯 ТЕСТ ЗАВЕРШЕН') } catch (error) { console.error('❌ ОШИБКА ТЕСТА:', error) } finally { await prisma.$disconnect() } } testApiKeySave()