// Патч для учета просмотренных профилей в функциональности бота // 1. Добавляем функцию recordProfileView в ProfileController import { Profile, ProfileData } from '../models/Profile'; import { ProfileService } from '../services/profileService'; export class ProfileController { constructor(private profileService: ProfileService) {} // Существующие методы... // Новый метод для записи просмотра профиля async recordProfileView(viewerTelegramId: string, viewedTelegramId: string, viewType: string = 'browse'): Promise { try { // Получаем внутренние ID пользователей const viewerId = await this.profileService.getUserIdByTelegramId(viewerTelegramId); const viewedId = await this.profileService.getUserIdByTelegramId(viewedTelegramId); if (!viewerId || !viewedId) { console.error('Не удалось найти пользователей для записи просмотра профиля'); return false; } // Проверяем существование таблицы profile_views const checkTableResult = await this.profileService.checkTableExists('profile_views'); if (checkTableResult) { // Записываем просмотр await this.profileService.recordProfileView(viewerId, viewedId, viewType); console.log(`Просмотр профиля записан: ${viewerTelegramId} просмотрел ${viewedTelegramId}`); return true; } else { console.log('Таблица profile_views не существует, просмотр не записан'); return false; } } catch (error) { console.error('Ошибка при записи просмотра профиля:', error); return false; } } // Новый метод для получения списка просмотренных профилей async getViewedProfiles(telegramId: string, limit: number = 50): Promise { try { // Получаем внутренний ID пользователя const userId = await this.profileService.getUserIdByTelegramId(telegramId); if (!userId) { console.error('Не удалось найти пользователя для получения списка просмотренных профилей'); return []; } // Проверяем существование таблицы profile_views const checkTableResult = await this.profileService.checkTableExists('profile_views'); if (checkTableResult) { // Получаем список просмотренных профилей return await this.profileService.getViewedProfiles(userId, limit); } else { console.log('Таблица profile_views не существует, возвращаем пустой список'); return []; } } catch (error) { console.error('Ошибка при получении списка просмотренных профилей:', error); return []; } } } // 2. Добавляем функцию для проверки существования таблицы в ProfileService async checkTableExists(tableName: string): Promise { try { const result = await query(` SELECT EXISTS ( SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = $1 ); `, [tableName]); return result.rows.length > 0 && result.rows[0].exists; } catch (error) { console.error(`Ошибка проверки существования таблицы ${tableName}:`, error); return false; } } // 3. Обновляем обработчик показа профиля, чтобы записывать просмотры async function handleShowProfile(ctx: any) { // Существующий код... // После успешного отображения профиля записываем просмотр const viewerTelegramId = ctx.from.id.toString(); const viewedTelegramId = candidateProfile.telegram_id.toString(); try { const profileController = new ProfileController(new ProfileService()); await profileController.recordProfileView(viewerTelegramId, viewedTelegramId, 'browse'); } catch (error) { console.error('Ошибка при записи просмотра профиля:', error); } // Остальной код... } // 4. Обновляем функцию getNextCandidate, чтобы учитывать просмотренные профили async function getNextCandidate(ctx: any) { const telegramId = ctx.from.id.toString(); const isNewUser = false; // Определяем, является ли пользователь новым try { // Сначала пытаемся получить профили, которые пользователь еще не просматривал const matchingService = new MatchingService(); const profileService = new ProfileService(); const profileController = new ProfileController(profileService); // Получаем UUID пользователя const userId = await profileService.getUserIdByTelegramId(telegramId); if (!userId) { console.error('Не удалось найти пользователя для получения следующего кандидата'); return null; } // Получаем список просмотренных профилей const viewedProfiles = await profileController.getViewedProfiles(telegramId); // Получаем профиль пользователя const userProfile = await profileService.getProfileByTelegramId(telegramId); if (!userProfile) { console.error('Не удалось найти профиль пользователя для получения следующего кандидата'); return null; } // Ищем подходящий профиль с учетом просмотренных const nextCandidate = await matchingService.getNextCandidate(telegramId, isNewUser); // Если найден кандидат, записываем просмотр if (nextCandidate) { const viewedTelegramId = await profileService.getTelegramIdByUserId(nextCandidate.userId); if (viewedTelegramId) { await profileController.recordProfileView(telegramId, viewedTelegramId, 'browse'); } } return nextCandidate; } catch (error) { console.error('Ошибка при получении следующего кандидата:', error); return null; } }