const mongoose = require('mongoose'); const Company = require('../models/Company'); require('dotenv').config({ path: '../../.env' }); const industryMap = { 'it': 'IT', 'finance': 'Финансы', 'manufacturing': 'Производство', 'construction': 'Строительство', 'retail': 'Розничная торговля', 'wholesale': 'Оптовая торговля', 'logistics': 'Логистика', 'healthcare': 'Здравоохранение', 'education': 'Образование', 'consulting': 'Консалтинг', 'marketing': 'Маркетинг', 'realestate': 'Недвижимость', 'food': 'Пищевая промышленность', 'agriculture': 'Сельское хозяйство', 'energy': 'Энергетика', 'telecom': 'Телекоммуникации', 'media': 'Медиа', 'tourism': 'Туризм', 'legal': 'Юридические услуги', 'other': 'Другое' }; const validIndustries = Object.values(industryMap); const industryAliases = { 'Торговля': 'Розничная торговля', 'торговля': 'Розничная торговля', 'Trade': 'Розничная торговля' }; async function migrateCompanies() { try { const allCompanies = await Company.find().exec(); console.log(`[Migration] Found ${allCompanies.length} companies to process`); let fixedCount = 0; let errorCount = 0; for (const company of allCompanies) { let needsUpdate = false; let updates = {}; // Check and fix industry field if (company.industry) { if (Array.isArray(company.industry)) { console.log(`[FIX] ${company.fullName}: industry is array, converting to string`); updates.industry = company.industry[0] || 'Другое'; needsUpdate = true; } else if (!validIndustries.includes(company.industry)) { const mapped = industryAliases[company.industry]; if (mapped) { console.log(`[FIX] ${company.fullName}: "${company.industry}" → "${mapped}"`); updates.industry = mapped; needsUpdate = true; } else { console.log(`[WARN] ${company.fullName}: unknown industry "${company.industry}"`); } } } // Check and fix companySize field if (company.companySize && Array.isArray(company.companySize)) { console.log(`[FIX] ${company.fullName}: companySize is array, converting to string`); updates.companySize = company.companySize[0] || ''; needsUpdate = true; } if (needsUpdate) { try { await Company.updateOne({ _id: company._id }, { $set: updates }); fixedCount++; console.log(` ✅ Updated`); } catch (err) { console.error(` ❌ Error: ${err.message}`); errorCount++; } } } console.log('\n[Migration] === MIGRATION SUMMARY ==='); console.log(`[Migration] Total companies: ${allCompanies.length}`); console.log(`[Migration] Fixed: ${fixedCount}`); console.log(`[Migration] Errors: ${errorCount}`); if (fixedCount === 0 && errorCount === 0) { console.log('[Migration] ✅ No migration needed - all data is valid!'); } else if (errorCount === 0) { console.log('[Migration] ✅ Migration completed successfully!'); } else { console.log('[Migration] ⚠️ Migration completed with errors.'); } } catch (err) { console.error('[Migration] ❌ Error:', err.message); throw err; } } module.exports = { migrateCompanies: migrateCompanies }; // Run directly if called as script if (require.main === module) { const mongoUrl = process.env.MONGODB_URI || 'mongodb://admin:password@localhost:27017/procurement_db?authSource=admin'; mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true, serverSelectionTimeoutMS: 5000, connectTimeoutMS: 5000, }).then(async () => { console.log('[Migration] Connected to MongoDB\n'); await migrateCompanies(); await mongoose.connection.close(); }).catch(err => { console.error('[Migration] ❌ Error:', err.message); process.exit(1); }); }