Отзывы
This commit is contained in:
342
server.js
342
server.js
@@ -8,15 +8,26 @@ const bcrypt = require('bcryptjs');
|
||||
const client = require('prom-client');
|
||||
require('dotenv').config();
|
||||
|
||||
const config = require('./config');
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3000;
|
||||
const API_KEY = process.env.HOTEL777KEY;
|
||||
const ADMIN_LOGIN = process.env.ADMIN_LOGIN;
|
||||
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD;
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'fallback-secret-change-in-production';
|
||||
const JWT_SECRET = process.env.JWT_SECRET;
|
||||
const MONITORING_USER = process.env.MONITORING_USER || 'monitoring';
|
||||
const MONITORING_PASSWORD = process.env.MONITORING_PASSWORD || 'monitoring123';
|
||||
|
||||
if (!JWT_SECRET) {
|
||||
console.error('FATAL: JWT_SECRET environment variable not set');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (JWT_SECRET === 'change-this-secret-in-production-min-32-chars') {
|
||||
console.warn('WARNING: Using default JWT_SECRET. Change it in production!');
|
||||
}
|
||||
|
||||
const register = new client.Registry();
|
||||
client.collectDefaultMetrics({ register });
|
||||
|
||||
@@ -63,12 +74,18 @@ const roomAvailability = new client.Gauge({
|
||||
registers: [register]
|
||||
});
|
||||
|
||||
const loginAttempts = new client.Gauge({
|
||||
name: 'login_attempts',
|
||||
help: 'Number of login attempts',
|
||||
registers: [register]
|
||||
});
|
||||
|
||||
if (!API_KEY) {
|
||||
console.error('FATAL: HOTEL777KEY environment variable not set');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
app.use(express.json());
|
||||
app.use(express.json({ limit: '10kb' }));
|
||||
app.use((req, res, next) => {
|
||||
res.header('Access-Control-Allow-Origin', '*');
|
||||
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
|
||||
@@ -146,106 +163,167 @@ db.serialize(() => {
|
||||
wishes TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`);
|
||||
db.run(`ALTER TABLE bookings ADD COLUMN wishes TEXT`, (err) => {});
|
||||
db.run(`ALTER TABLE bookings ADD COLUMN status TEXT DEFAULT 'новая'`, (err) => {});
|
||||
db.run(`ALTER TABLE bookings ADD COLUMN room_type TEXT`, (err) => {});
|
||||
db.run(`ALTER TABLE bookings ADD COLUMN comment TEXT`, (err) => {});
|
||||
db.run(`ALTER TABLE bookings ADD COLUMN base_price REAL`, (err) => {});
|
||||
db.run(`ALTER TABLE bookings ADD COLUMN discount_percent INTEGER DEFAULT 0`, (err) => {});
|
||||
db.run(`ALTER TABLE bookings ADD COLUMN discount_amount REAL DEFAULT 0`, (err) => {});
|
||||
db.run(`ALTER TABLE bookings ADD COLUMN total_price REAL`, (err) => {});
|
||||
db.run(`ALTER TABLE bookings ADD COLUMN promocode_id INTEGER`, (err) => {});
|
||||
db.run(`CREATE TABLE IF NOT EXISTS promocodes (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
code TEXT NOT NULL UNIQUE,
|
||||
discount_percent INTEGER NOT NULL CHECK(discount_percent BETWEEN 1 AND 99),
|
||||
valid_from DATETIME,
|
||||
valid_to DATETIME,
|
||||
valid_days INTEGER,
|
||||
is_active INTEGER DEFAULT 1,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`);
|
||||
db.run(`CREATE TABLE IF NOT EXISTS rooms (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
type TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
rooms_count INTEGER DEFAULT 1,
|
||||
single_beds INTEGER DEFAULT 0,
|
||||
double_beds INTEGER DEFAULT 0,
|
||||
has_sofa INTEGER DEFAULT 0,
|
||||
has_ac INTEGER DEFAULT 0,
|
||||
has_wifi INTEGER DEFAULT 0,
|
||||
has_shower INTEGER DEFAULT 0,
|
||||
max_guests INTEGER DEFAULT 2,
|
||||
price_per_guest INTEGER NOT NULL,
|
||||
image_path TEXT,
|
||||
is_active INTEGER DEFAULT 1,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`);
|
||||
db.run(`CREATE TABLE IF NOT EXISTS booking_history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
booking_id INTEGER NOT NULL,
|
||||
user_id INTEGER,
|
||||
user_login TEXT,
|
||||
field TEXT NOT NULL,
|
||||
old_value TEXT,
|
||||
new_value TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (booking_id) REFERENCES bookings(id)
|
||||
)`);
|
||||
db.run(`CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
login TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
full_name TEXT,
|
||||
email TEXT,
|
||||
role TEXT NOT NULL DEFAULT 'user',
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`);
|
||||
db.run(`CREATE TABLE IF NOT EXISTS settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`, (err) => {
|
||||
if (err) {
|
||||
console.error('CREATE TABLE settings FAILED:', err.message);
|
||||
} else {
|
||||
console.log('CREATE TABLE settings SUCCESS');
|
||||
}
|
||||
});
|
||||
|
||||
db.run(`CREATE TABLE IF NOT EXISTS reviews (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
author_name TEXT NOT NULL,
|
||||
country TEXT NOT NULL,
|
||||
country_code TEXT,
|
||||
city TEXT NOT NULL,
|
||||
stars REAL NOT NULL CHECK(stars >= 0 AND stars <= 5),
|
||||
text TEXT NOT NULL,
|
||||
review_code TEXT NOT NULL,
|
||||
ip_address TEXT,
|
||||
is_approved INTEGER DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`, (err) => {
|
||||
if (err && !err.message.includes('already exists')) {
|
||||
console.error('Reviews table error:', err.message);
|
||||
const columnsToAdd = [
|
||||
'wishes TEXT',
|
||||
'status TEXT DEFAULT "новая"',
|
||||
'room_type TEXT',
|
||||
'comment TEXT',
|
||||
'base_price REAL',
|
||||
'discount_percent INTEGER DEFAULT 0',
|
||||
'discount_amount REAL DEFAULT 0',
|
||||
'total_price REAL',
|
||||
'promocode_id INTEGER'
|
||||
];
|
||||
|
||||
function addColumnSafely(columns, index) {
|
||||
if (index >= columns.length) {
|
||||
setupPromocodesTable();
|
||||
return;
|
||||
}
|
||||
|
||||
db.run(`PRAGMA foreign_keys = ON`, (err) => {
|
||||
if (err) console.error('Foreign keys error:', err.message);
|
||||
});
|
||||
|
||||
db.all("PRAGMA table_info(reviews)", [], (err, cols) => {
|
||||
if (err || !cols) return;
|
||||
db.all("PRAGMA table_info(bookings)", [], (err, cols) => {
|
||||
if (err) {
|
||||
setupPromocodesTable();
|
||||
return;
|
||||
}
|
||||
|
||||
const colNames = cols.map(c => c.name);
|
||||
if (!colNames.includes('country_code')) {
|
||||
db.run("ALTER TABLE reviews ADD COLUMN country_code TEXT", (err) => {
|
||||
if (err) console.log('Migration: country_code column (ignore if exists):', err.message);
|
||||
else console.log('Migration: country_code column added');
|
||||
const columnDef = columns[index];
|
||||
const colName = columnDef.split(' ')[0];
|
||||
|
||||
if (!colNames.includes(colName)) {
|
||||
db.run(`ALTER TABLE bookings ADD COLUMN ${columnDef}`, (err) => {
|
||||
if (err && !err.message.includes('duplicate')) {
|
||||
console.log('Migration note (ignore if exists):', err.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
addColumnSafely(columns, index + 1);
|
||||
});
|
||||
}
|
||||
|
||||
function setupPromocodesTable() {
|
||||
db.run(`CREATE TABLE IF NOT EXISTS promocodes (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
code TEXT NOT NULL UNIQUE,
|
||||
discount_percent INTEGER NOT NULL CHECK(discount_percent BETWEEN 1 AND 99),
|
||||
valid_from DATETIME,
|
||||
valid_to DATETIME,
|
||||
valid_days INTEGER,
|
||||
is_active INTEGER DEFAULT 1,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`);
|
||||
setupRoomsTable();
|
||||
}
|
||||
|
||||
function setupRoomsTable() {
|
||||
db.run(`CREATE TABLE IF NOT EXISTS rooms (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
type TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
rooms_count INTEGER DEFAULT 1,
|
||||
single_beds INTEGER DEFAULT 0,
|
||||
double_beds INTEGER DEFAULT 0,
|
||||
has_sofa INTEGER DEFAULT 0,
|
||||
has_ac INTEGER DEFAULT 0,
|
||||
has_wifi INTEGER DEFAULT 0,
|
||||
has_shower INTEGER DEFAULT 0,
|
||||
max_guests INTEGER DEFAULT 2,
|
||||
price_per_guest INTEGER NOT NULL,
|
||||
image_path TEXT,
|
||||
is_active INTEGER DEFAULT 1,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`);
|
||||
setupBookingHistoryTable();
|
||||
}
|
||||
|
||||
function setupBookingHistoryTable() {
|
||||
db.run(`CREATE TABLE IF NOT EXISTS booking_history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
booking_id INTEGER NOT NULL,
|
||||
user_id INTEGER,
|
||||
user_login TEXT,
|
||||
field TEXT NOT NULL,
|
||||
old_value TEXT,
|
||||
new_value TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (booking_id) REFERENCES bookings(id)
|
||||
)`);
|
||||
setupUsersTable();
|
||||
}
|
||||
|
||||
function setupUsersTable() {
|
||||
db.run(`CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
login TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
full_name TEXT,
|
||||
email TEXT,
|
||||
role TEXT NOT NULL DEFAULT 'user',
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`);
|
||||
setupSettingsTable();
|
||||
}
|
||||
|
||||
function setupSettingsTable() {
|
||||
db.run(`CREATE TABLE IF NOT EXISTS settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`, (err) => {
|
||||
if (err) {
|
||||
console.error('CREATE TABLE settings FAILED:', err.message);
|
||||
} else {
|
||||
console.log('CREATE TABLE settings SUCCESS');
|
||||
}
|
||||
});
|
||||
setupReviewsTable();
|
||||
}
|
||||
|
||||
function setupReviewsTable() {
|
||||
db.run(`CREATE TABLE IF NOT EXISTS reviews (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
author_name TEXT NOT NULL,
|
||||
country TEXT NOT NULL,
|
||||
country_code TEXT,
|
||||
city TEXT NOT NULL,
|
||||
stars REAL NOT NULL CHECK(stars >= 0 AND stars <= 5),
|
||||
text TEXT NOT NULL,
|
||||
review_code TEXT NOT NULL,
|
||||
ip_address TEXT,
|
||||
is_approved INTEGER DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`, (err) => {
|
||||
if (err && !err.message.includes('already exists')) {
|
||||
console.error('Reviews table error:', err.message);
|
||||
}
|
||||
|
||||
db.run(`PRAGMA foreign_keys = ON`, (err) => {
|
||||
if (err) console.error('Foreign keys error:', err.message);
|
||||
});
|
||||
|
||||
db.all("PRAGMA table_info(reviews)", [], (err, cols) => {
|
||||
if (err || !cols) return;
|
||||
const colNames = cols.map(c => c.name);
|
||||
if (!colNames.includes('country_code')) {
|
||||
db.run("ALTER TABLE reviews ADD COLUMN country_code TEXT", (err) => {
|
||||
if (err) console.log('Migration: country_code column (ignore if exists):', err.message);
|
||||
else console.log('Migration: country_code column added');
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
addColumnSafely(columnsToAdd, 0);
|
||||
|
||||
db.run(`CREATE INDEX IF NOT EXISTS idx_bookings_checkin ON bookings(checkin_date)`, (err) => {
|
||||
if (err) console.log('Index idx_bookings_checkin:', err.message);
|
||||
});
|
||||
db.run(`CREATE INDEX IF NOT EXISTS idx_bookings_status ON bookings(status)`, (err) => {
|
||||
if (err) console.log('Index idx_bookings_status:', err.message);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -285,13 +363,8 @@ function initDefaultRooms() {
|
||||
db.get("SELECT COUNT(*) as count FROM rooms", (err, row) => {
|
||||
if (err) return console.error('Check rooms count error:', err);
|
||||
if (row.count > 0) return;
|
||||
const defaults = [
|
||||
{ type: 'Эконом', name: 'Эконом 1', description: 'Бюджетный номер', rooms_count: 3, single_beds: 2, double_beds: 0, has_sofa: 0, has_ac: 0, has_wifi: 1, has_shower: 1, max_guests: 2, price_per_guest: 2500, image_path: null, is_active: 1 },
|
||||
{ type: 'Стандарт', name: 'Стандарт 1', description: 'Комфортный номер', rooms_count: 2, single_beds: 0, double_beds: 1, has_sofa: 1, has_ac: 1, has_wifi: 1, has_shower: 1, max_guests: 3, price_per_guest: 4000, image_path: null, is_active: 1 },
|
||||
{ type: 'VIP Люкс', name: 'VIP Люкс 1', description: 'Премиум номер', rooms_count: 1, single_beds: 0, double_beds: 1, has_sofa: 1, has_ac: 1, has_wifi: 1, has_shower: 1, max_guests: 4, price_per_guest: 8000, image_path: null, is_active: 1 }
|
||||
];
|
||||
const stmt = db.prepare(`INSERT INTO rooms (type, name, description, rooms_count, single_beds, double_beds, has_sofa, has_ac, has_wifi, has_shower, max_guests, price_per_guest, image_path, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
||||
defaults.forEach(r => stmt.run(r.type, r.name, r.description, r.rooms_count, r.single_beds, r.double_beds, r.has_sofa, r.has_ac, r.has_wifi, r.has_shower, r.max_guests, r.price_per_guest, r.image_path, r.is_active));
|
||||
config.DEFAULT_ROOMS.forEach(r => stmt.run(r.type, r.name, r.description, r.rooms_count, r.single_beds, r.double_beds, r.has_sofa, r.has_ac, r.has_wifi, r.has_shower, r.max_guests, r.price_per_guest, r.image_path, r.is_active));
|
||||
stmt.finalize();
|
||||
console.log('✅ Default rooms initialized');
|
||||
});
|
||||
@@ -354,7 +427,9 @@ app.get('/api/countries', (req, res) => {
|
||||
const match = data.match(/const\s+COUNTRIES\s*=\s*(\[.*\]);/s);
|
||||
if (match) {
|
||||
try {
|
||||
const countries = eval(match[1]);
|
||||
let jsonStr = match[1];
|
||||
jsonStr = jsonStr.replace(/'/g, '"');
|
||||
const countries = JSON.parse(jsonStr);
|
||||
res.json(countries);
|
||||
} catch (e) {
|
||||
res.status(500).json({ error: 'Parse error' });
|
||||
@@ -365,6 +440,10 @@ app.get('/api/countries', (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
function safeJsonString(str) {
|
||||
return str.replace(/'/g, "'").replace(/\\"/g, '"');
|
||||
}
|
||||
|
||||
app.get('/api/cities/:countryCode', (req, res) => {
|
||||
const countryCode = req.params.countryCode;
|
||||
|
||||
@@ -382,28 +461,15 @@ app.get('/api/cities/:countryCode', (req, res) => {
|
||||
let cities = [];
|
||||
const arrayMatch = data.match(/const\s+CITIES_\w+\s*=\s*(\[.*?\]);/s);
|
||||
if (arrayMatch) {
|
||||
cities = JSON.parse(arrayMatch[1].replace(/"/g, '"').replace(/'/g, "'"));
|
||||
}
|
||||
|
||||
if (cities.length === 0) {
|
||||
const majorMatch = data.match(/CITIES_BY_CODE\s*=\s*({[\s\S]*?});/);
|
||||
if (majorMatch) {
|
||||
const codeMatch = majorMatch[1].match(new RegExp(`${countryCode}:\\s*\\[([^\\]]+)\\]`));
|
||||
if (codeMatch) {
|
||||
cities = codeMatch[1].split(',').map(c => c.trim().replace(/^["']|["']$/g, ''));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (cities.length === 0) {
|
||||
const defaultMatch = data.match(/CITIES_DEFAULT\s*=\s*(\[.*?\]);/s);
|
||||
if (defaultMatch) {
|
||||
try {
|
||||
cities = JSON.parse(safeJsonString(arrayMatch[1]));
|
||||
} catch (e) {
|
||||
const jsMatch = arrayMatch[1].replace(/'/g, '"');
|
||||
try {
|
||||
const evalResult = eval(defaultMatch[1]);
|
||||
if (Array.isArray(evalResult)) {
|
||||
cities = evalResult;
|
||||
}
|
||||
} catch (e) {}
|
||||
cities = JSON.parse(jsMatch);
|
||||
} catch (e2) {
|
||||
console.error('Failed to parse cities:', e2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -448,12 +514,36 @@ async function convertImages() {
|
||||
}
|
||||
|
||||
convertImages().then(() => {
|
||||
app.listen(PORT, async () => {
|
||||
console.log('✅ HOTEL777KEY is', API_KEY);
|
||||
const server = app.listen(PORT, async () => {
|
||||
console.log('✅ HOTEL777KEY is set');
|
||||
console.log('📊 Prometheus metrics available at: http://localhost:' + PORT + '/metrics');
|
||||
console.log('🔐 Monitoring credentials: ' + MONITORING_USER + ' / ' + (MONITORING_PASSWORD ? '***' : 'NOT SET'));
|
||||
const monitoringSet = MONITORING_PASSWORD ? 'configured' : 'NOT SET';
|
||||
console.log('🔐 Monitoring auth: ' + monitoringSet);
|
||||
console.log('');
|
||||
await runStartupTests(db, modules);
|
||||
console.log(`✅ Hotel 777 server running on http://localhost:${PORT}`);
|
||||
});
|
||||
|
||||
function gracefulShutdown(signal) {
|
||||
console.log(`\n${signal} received. Shutting down gracefully...`);
|
||||
server.close(() => {
|
||||
db.close((err) => {
|
||||
if (err) {
|
||||
console.error('Error closing database:', err);
|
||||
} else {
|
||||
console.log('Database connection closed.');
|
||||
}
|
||||
console.log('Server closed.');
|
||||
process.exit(0);
|
||||
});
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
console.error('Forced shutdown after timeout.');
|
||||
process.exit(1);
|
||||
}, 10000);
|
||||
}
|
||||
|
||||
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
|
||||
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
|
||||
});
|
||||
Reference in New Issue
Block a user