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

@@ -3,6 +3,17 @@ const router = express.Router();
const { verifyToken } = require('../middleware/auth');
const Company = require('../models/Company');
// Функция для логирования с проверкой DEV переменной
const log = (message, data = '') => {
if (process.env.DEV === 'true') {
if (data) {
console.log(message, data);
} else {
console.log(message);
}
}
};
// GET /search/recommendations - получить рекомендации компаний (ДОЛЖЕН быть ПЕРЕД /*)
router.get('/recommendations', verifyToken, async (req, res) => {
try {
@@ -28,7 +39,7 @@ router.get('/recommendations', verifyToken, async (req, res) => {
reason: 'Matches your search criteria'
}));
console.log('[Search] Returned recommendations:', recommendations.length);
log('[Search] Returned recommendations:', recommendations.length);
res.json(recommendations);
} catch (error) {
@@ -47,6 +58,9 @@ router.get('/', verifyToken, async (req, res) => {
query = '',
page = 1,
limit = 10,
industries,
companySize,
geography,
minRating = 0,
hasReviews,
hasAcceptedDocs,
@@ -58,6 +72,29 @@ router.get('/', verifyToken, async (req, res) => {
const User = require('../models/User');
const user = await User.findById(req.userId);
log('[Search] Request params:', { query, industries, companySize, geography, minRating, hasReviews, hasAcceptedDocs, sortBy, sortOrder });
// Маппинг кодов фильтров на значения в БД
const industryMap = {
'it': 'IT',
'finance': 'Финансы',
'manufacturing': 'Производство',
'construction': 'Строительство',
'retail': 'Розничная торговля',
'wholesale': 'Оптовая торговля',
'logistics': 'Логистика',
'healthcare': 'Здравоохранение',
'education': 'Образование',
'consulting': 'Консалтинг',
'marketing': 'Маркетинг',
'realestate': 'Недвижимость',
'food': 'Пищевая промышленность',
'agriculture': 'Сельское хозяйство',
'energy': 'Энергетика',
'telecom': 'Телекоммуникации',
'media': 'Медиа'
};
// Начальный фильтр: исключить собственную компанию
let filters = [];
@@ -78,6 +115,43 @@ router.get('/', verifyToken, async (req, res) => {
});
}
// Фильтр по отраслям - преобразуем коды в значения БД
if (industries) {
const industryList = Array.isArray(industries) ? industries : [industries];
if (industryList.length > 0) {
const dbIndustries = industryList
.map(code => industryMap[code])
.filter(val => val !== undefined);
log('[Search] Raw industries param:', industries);
log('[Search] Industry codes:', industryList, 'Mapped to:', dbIndustries);
if (dbIndustries.length > 0) {
filters.push({ industry: { $in: dbIndustries } });
log('[Search] Added industry filter:', { industry: { $in: dbIndustries } });
} else {
log('[Search] No industries mapped! Codes were:', industryList);
}
}
}
// Фильтр по размеру компании
if (companySize) {
const sizeList = Array.isArray(companySize) ? companySize : [companySize];
if (sizeList.length > 0) {
filters.push({ companySize: { $in: sizeList } });
}
}
// Фильтр по географии
if (geography) {
const geoList = Array.isArray(geography) ? geography : [geography];
if (geoList.length > 0) {
filters.push({ partnerGeography: { $in: geoList } });
log('[Search] Geography filter:', { partnerGeography: { $in: geoList } });
}
}
// Фильтр по рейтингу
if (minRating) {
const rating = parseFloat(minRating);
@@ -112,6 +186,12 @@ router.get('/', verifyToken, async (req, res) => {
sortOptions.rating = sortOrder === 'asc' ? 1 : -1;
}
log('[Search] Final MongoDB filter:', JSON.stringify(filter, null, 2));
let filterDebug = filters.length > 0 ? { $and: filters } : {};
const allCompanies = await Company.find({});
log('[Search] All companies in DB:', allCompanies.map(c => ({ name: c.fullName, geography: c.partnerGeography, industry: c.industry })));
const total = await Company.countDocuments(filter);
const companies = await Company.find(filter)
.sort(sortOptions)
@@ -123,13 +203,19 @@ router.get('/', verifyToken, async (req, res) => {
id: c._id
}));
console.log('[Search] Returned', paginatedResults.length, 'companies');
log('[Search] Query:', query, 'Industries:', industries, 'Size:', companySize, 'Geo:', geography);
log('[Search] Total found:', total, 'Returning:', paginatedResults.length, 'companies');
log('[Search] Company details:', paginatedResults.map(c => ({ name: c.fullName, industry: c.industry })));
res.json({
companies: paginatedResults,
total,
page: pageNum,
totalPages: Math.ceil(total / limitNum)
totalPages: Math.ceil(total / limitNum),
_debug: {
filter: JSON.stringify(filter),
industriesReceived: industries
}
});
} catch (error) {
console.error('[Search] Error:', error.message);