Files
tourrism_site/database/init-database.js
Andrey K. Choi ed871fc4d1 🎨 Добавлен полный редактор стилей и поле image_url для туров
 Новые функции:
- Поле image_url в модели туров для изменения изображений через админ-панель
- Расширенная модель настроек сайта с категориями: colors, typography, images, effects, layout
- Динамический CSS генератор на основе настроек (/dynamic-styles.css)
- API для управления настройками сайта (/api/site-settings)

🎯 Редактор стилей:
- Управление цветами (основные, акцентные, текст, фон)
- Настройка типографики (шрифты, размеры, межстрочный интервал)
- Управление изображениями (фоны, логотипы, фавикон)
- Эффекты (прозрачность, тени, размытие, скругления)
- Макет (высота секций, размеры контейнеров)
- Пользовательский CSS код

🛠️ Техническая реализация:
- SiteSettingsHelper с кешированием для производительности
- CSS переменные для динамического изменения стилей
- Автоматическая миграция базы данных
- Интеграция с AdminJS для удобного управления
- Загрузка настроек в шаблоны для доступности

📊 База данных:
- Расширена таблица site_settings (добавлено поле category)
- Новые типы настроек: color, file
- 27 предустановленных настроек для полного контроля над дизайном
- Автоматическое применение миграций при старте приложения
2025-11-29 22:03:00 +09:00

101 lines
3.6 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import db from '../src/config/database.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export async function initDatabase() {
try {
console.log('🚀 Starting complete database initialization...');
// Check if database is connected
await db.query('SELECT 1');
console.log('✅ Database connection successful');
// 1. Create schema
console.log('📋 Creating database schema...');
const schemaPath = path.join(__dirname, 'schema.sql');
const schema = fs.readFileSync(schemaPath, 'utf8');
await db.query(schema);
console.log('✅ Database schema created successfully');
// 2. Check if tables are empty (first run)
const checkResult = await db.query('SELECT COUNT(*) FROM admins');
const isEmpty = parseInt(checkResult.rows[0].count) === 0;
if (isEmpty) {
console.log('📝 Database is empty, inserting mock data...');
// Insert mock data
const mockDataPath = path.join(__dirname, 'mock-data.sql');
const mockData = fs.readFileSync(mockDataPath, 'utf8');
await db.query(mockData);
console.log('✅ Mock data inserted successfully');
} else {
console.log(' Database already contains data, skipping mock data insertion');
}
// 3. Run any pending migrations
console.log('🔄 Checking for pending migrations...');
// Check if rating system exists
try {
await db.query('SELECT 1 FROM route_ratings LIMIT 1');
console.log(' Rating system already exists');
} catch (error) {
console.log('📈 Installing rating system...');
const ratingMigrationPath = path.join(__dirname, 'rating-system-migration.sql');
if (fs.existsSync(ratingMigrationPath)) {
const ratingMigration = fs.readFileSync(ratingMigrationPath, 'utf8');
await db.query(ratingMigration);
console.log('✅ Rating system installed successfully');
}
}
// Check if style editor migration is applied
try {
const result = await db.query("SELECT 1 FROM site_settings WHERE setting_key = 'primary_color' LIMIT 1");
if (result.rows.length === 0) {
console.log('🎨 Installing style editor features...');
const styleMigrationPath = path.join(__dirname, 'style-editor-migration.sql');
if (fs.existsSync(styleMigrationPath)) {
const styleMigration = fs.readFileSync(styleMigrationPath, 'utf8');
await db.query(styleMigration);
console.log('✅ Style editor installed successfully');
}
} else {
console.log(' Style editor already installed');
}
} catch (error) {
console.log('🎨 Installing style editor features...');
const styleMigrationPath = path.join(__dirname, 'style-editor-migration.sql');
if (fs.existsSync(styleMigrationPath)) {
const styleMigration = fs.readFileSync(styleMigrationPath, 'utf8');
await db.query(styleMigration);
console.log('✅ Style editor installed successfully');
}
}
console.log('✨ Database initialization completed successfully!');
} catch (error) {
console.error('❌ Database initialization failed:', error);
throw error;
}
}
// Run if called directly
if (process.argv[1] === fileURLToPath(import.meta.url)) {
initDatabase()
.then(() => {
console.log('🎉 All done!');
process.exit(0);
})
.catch((error) => {
console.error('💥 Initialization failed:', error);
process.exit(1);
});
}