require('dotenv').config(); const { Pool } = require('pg'); const { v4: uuidv4 } = require('uuid'); // Функция для запуска скрипта async function initializeDatabase() { console.log('Starting database initialization script...'); const pool = new Pool({ host: 'localhost', // Используем localhost port: 5432, // Используем стандартный порт 5432 database: 'telegram_tinder_bot', user: 'postgres', password: '', max: 5, connectionTimeoutMillis: 5000 }); console.log('DB Connection Details:'); console.log('- Host: localhost'); console.log('- Port: 5432'); console.log('- Database: telegram_tinder_bot'); console.log('- User: postgres'); try { // Проверяем подключение console.log('Testing connection...'); const client = await pool.connect(); try { console.log('✅ Connected to database successfully!'); // 1. Создаем расширение для генерации UUID если его нет console.log('Creating UUID extension...'); await client.query(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`); // 2. Создаем таблицу для шаблонов уведомлений console.log('Creating notification_templates table...'); await client.query(` CREATE TABLE IF NOT EXISTS notification_templates ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), type VARCHAR(50) NOT NULL UNIQUE, title TEXT NOT NULL, message_template TEXT NOT NULL, button_template JSONB NOT NULL, created_at TIMESTAMP DEFAULT NOW() ) `); // 3. Вставляем базовые шаблоны console.log('Inserting notification templates...'); const templates = [ { id: uuidv4(), type: 'new_like', title: 'Новый лайк!', message_template: '❤️ *{{name}}* поставил(а) вам лайк!\n\nВозраст: {{age}}\n{{city}}\n\nОтветьте взаимностью или посмотрите профиль.', button_template: JSON.stringify({ inline_keyboard: [ [{ text: '👀 Посмотреть профиль', callback_data: 'view_profile:{{userId}}' }], [ { text: '❤️ Лайк в ответ', callback_data: 'like_back:{{userId}}' }, { text: '⛔️ Пропустить', callback_data: 'dislike_profile:{{userId}}' } ], [{ text: '💕 Открыть все лайки', callback_data: 'view_likes' }] ] }) }, { id: uuidv4(), type: 'super_like', title: 'Супер-лайк!', message_template: '⭐️ *{{name}}* отправил(а) вам супер-лайк!\n\nВозраст: {{age}}\n{{city}}\n\nВы произвели особое впечатление! Ответьте взаимностью или посмотрите профиль.', button_template: JSON.stringify({ inline_keyboard: [ [{ text: '👀 Посмотреть профиль', callback_data: 'view_profile:{{userId}}' }], [ { text: '❤️ Лайк в ответ', callback_data: 'like_back:{{userId}}' }, { text: '⛔️ Пропустить', callback_data: 'dislike_profile:{{userId}}' } ], [{ text: '💕 Открыть все лайки', callback_data: 'view_likes' }] ] }) }, { id: uuidv4(), type: 'new_match', title: 'Новый матч!', message_template: '🎊 *Ура! Это взаимно!* 🎊\n\nВы и *{{name}}* понравились друг другу!\nВозраст: {{age}}\n{{city}}\n\nСделайте первый шаг - напишите сообщение!', button_template: JSON.stringify({ inline_keyboard: [ [{ text: '💬 Начать общение', callback_data: 'open_native_chat_{{matchId}}' }], [ { text: '👀 Посмотреть профиль', callback_data: 'view_profile:{{userId}}' }, { text: '📋 Все матчи', callback_data: 'native_chats' } ] ] }) }, { id: uuidv4(), type: 'new_message', title: 'Новое сообщение!', message_template: '💌 *Новое сообщение!*\n\nОт: *{{name}}*\n\n"{{message}}"\n\nОтветьте на сообщение прямо сейчас!', button_template: JSON.stringify({ inline_keyboard: [ [{ text: '📩 Ответить', callback_data: 'open_native_chat_{{matchId}}' }], [ { text: '👤 Профиль', callback_data: 'view_profile:{{userId}}' }, { text: '📋 Все чаты', callback_data: 'native_chats' } ] ] }) } ]; // Вставляем шаблоны с проверкой на конфликты for (const template of templates) { await client.query(` INSERT INTO notification_templates (id, type, title, message_template, button_template, created_at) VALUES ($1, $2, $3, $4, $5, NOW()) ON CONFLICT (type) DO UPDATE SET title = $3, message_template = $4, button_template = $5 `, [template.id, template.type, template.title, template.message_template, template.button_template]); } console.log('✅ Notification templates created/updated successfully'); // 4. Создаем таблицу для хранения логов уведомлений если её нет console.log('Creating notifications table...'); await client.query(` CREATE TABLE IF NOT EXISTS notifications ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), user_id UUID NOT NULL, type VARCHAR(50) NOT NULL, data JSONB NOT NULL, is_read BOOLEAN DEFAULT FALSE, created_at TIMESTAMP DEFAULT NOW() ) `); console.log('✅ Notifications table created successfully'); // 5. Проверяем, что таблицы созданы const tablesResult = await client.query(` SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_name IN ('notification_templates', 'notifications') `); console.log('Created tables:'); tablesResult.rows.forEach(row => { console.log(`- ${row.table_name}`); }); } finally { client.release(); await pool.end(); } console.log('✅ Database initialization completed successfully'); } catch (error) { console.error('❌ Database initialization error:', error); } } // Запускаем скрипт initializeDatabase();