add new back

This commit is contained in:
2025-10-27 18:58:38 +03:00
parent a6065dd95c
commit 6c190b80fb
16 changed files with 996 additions and 147 deletions

View File

@@ -0,0 +1,93 @@
const mongoose = require('mongoose');
const Message = require('../models/Message');
require('dotenv').config({ path: '../../.env' });
const mongoUrl = process.env.MONGODB_URI || 'mongodb://localhost:27017/procurement_db';
async function migrateMessages() {
try {
console.log('[Migration] Connecting to MongoDB...');
await mongoose.connect(mongoUrl, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000,
connectTimeoutMS: 5000,
});
console.log('[Migration] Connected to MongoDB');
// Найти все сообщения
const allMessages = await Message.find().exec();
console.log('[Migration] Found', allMessages.length, 'total messages');
let fixedCount = 0;
let errorCount = 0;
// Проходим по каждому сообщению
for (const message of allMessages) {
try {
const threadId = message.threadId;
if (!threadId) {
console.log('[Migration] Skipping message', message._id, '- no threadId');
continue;
}
// Парсим threadId формата "thread-id1-id2" или "id1-id2"
let ids = threadId.replace('thread-', '').split('-');
if (ids.length < 2) {
console.log('[Migration] Invalid threadId format:', threadId);
errorCount++;
continue;
}
const companyId1 = ids[0];
const companyId2 = ids[1];
// Сравниваем с senderCompanyId
const senderIdString = message.senderCompanyId.toString ? message.senderCompanyId.toString() : message.senderCompanyId;
const expectedRecipient = senderIdString === companyId1 ? companyId2 : companyId1;
// Если recipientCompanyId не установлена или неправильная - исправляем
if (!message.recipientCompanyId || message.recipientCompanyId.toString() !== expectedRecipient) {
console.log('[Migration] Fixing message', message._id);
console.log(' Old recipientCompanyId:', message.recipientCompanyId);
console.log(' Expected:', expectedRecipient);
// Конвертируем в ObjectId если нужно
const { ObjectId } = require('mongoose').Types;
let recipientObjectId = expectedRecipient;
try {
if (typeof expectedRecipient === 'string' && ObjectId.isValid(expectedRecipient)) {
recipientObjectId = new ObjectId(expectedRecipient);
}
} catch (e) {
console.log(' Could not convert to ObjectId');
}
await Message.updateOne(
{ _id: message._id },
{ recipientCompanyId: recipientObjectId }
);
fixedCount++;
console.log(' ✅ Fixed');
}
} catch (err) {
console.error('[Migration] Error processing message', message._id, ':', err.message);
errorCount++;
}
}
console.log('[Migration] ✅ Migration completed!');
console.log('[Migration] Fixed:', fixedCount, 'messages');
console.log('[Migration] Errors:', errorCount);
await mongoose.connection.close();
console.log('[Migration] Disconnected from MongoDB');
} catch (err) {
console.error('[Migration] ❌ Error:', err.message);
process.exit(1);
}
}
migrateMessages();

View File

@@ -11,8 +11,8 @@ const recreateTestUser = async () => {
console.log('\n🔄 Подключение к MongoDB...');
await mongoose.connect(mongoUri, {
serverSelectionTimeoutMS: 5000,
connectTimeoutMS: 5000,
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log('✅ Подключено к MongoDB\n');
@@ -76,6 +76,21 @@ const recreateTestUser = async () => {
console.log(' Пароль: SecurePass123!');
console.log('');
// Обновить существующие mock компании
console.log('\n🔄 Обновление существующих mock компаний...');
const updates = [
{ inn: '7707083894', updates: { companySize: '51-250', partnerGeography: ['moscow', 'russia_all'] } },
{ inn: '7707083895', updates: { companySize: '500+', partnerGeography: ['moscow', 'russia_all'] } },
{ inn: '7707083896', updates: { companySize: '11-50', partnerGeography: ['moscow', 'russia_all'] } },
{ inn: '7707083897', updates: { companySize: '51-250', partnerGeography: ['moscow', 'russia_all'] } },
{ inn: '7707083898', updates: { companySize: '251-500', partnerGeography: ['moscow', 'russia_all'] } },
];
for (const item of updates) {
await Company.updateOne({ inn: item.inn }, { $set: item.updates });
console.log(` ✓ Компания обновлена: INN ${item.inn}`);
}
await mongoose.connection.close();
process.exit(0);
} catch (error) {

View File

@@ -0,0 +1,61 @@
#!/usr/bin/env node
/**
* Скрипт для тестирования логирования
*
* Использование:
* node stubs/scripts/test-logging.js # Логи скрыты (DEV не установлена)
* DEV=true node stubs/scripts/test-logging.js # Логи видны
*/
// Функция логирования из маршрутов
const log = (message, data = '') => {
if (process.env.DEV === 'true') {
if (data) {
console.log(message, data);
} else {
console.log(message);
}
}
};
console.log('');
console.log('='.repeat(60));
console.log('TEST: Логирование с переменной окружения DEV');
console.log('='.repeat(60));
console.log('');
console.log('Значение DEV:', process.env.DEV || '(не установлена)');
console.log('');
// Тестируем различные логи
log('[Auth] Token verified - userId: 68fe2ccda3526c303ca06799 companyId: 68fe2ccda3526c303ca06796');
log('[Auth] Generating token for userId:', '68fe2ccda3526c303ca06799');
log('[BuyProducts] Found', 0, 'products for company 68fe2ccda3526c303ca06796');
log('[Products] GET Fetching products for companyId:', '68fe2ccda3526c303ca06799');
log('[Products] Found', 1, 'products');
log('[Reviews] Returned', 0, 'reviews for company 68fe2ccda3526c303ca06796');
log('[Messages] Fetching threads for companyId:', '68fe2ccda3526c303ca06796');
log('[Messages] Found', 4, 'messages for company');
log('[Messages] Returned', 3, 'unique threads');
log('[Search] Request params:', { query: '', page: 1 });
console.log('');
console.log('='.repeat(60));
console.log('РЕЗУЛЬТАТ:');
console.log('='.repeat(60));
if (process.env.DEV === 'true') {
console.log('✅ DEV=true - логи ВИДНЫ выше');
} else {
console.log('❌ DEV не установлена или != "true" - логи СКРЫТЫ');
console.log('');
console.log('Для включения логов запустите:');
console.log(' export DEV=true && npm start (Linux/Mac)');
console.log(' $env:DEV = "true"; npm start (PowerShell)');
console.log(' set DEV=true && npm start (CMD)');
}
console.log('');
console.log('='.repeat(60));
console.log('');