47 lines
1.8 KiB
JavaScript
47 lines
1.8 KiB
JavaScript
const axios = require('axios');
|
|
const { db, normalizePhone, logAction } = require('./db');
|
|
const { notifyNewBooking } = require('./mailer');
|
|
|
|
async function syncBookings() {
|
|
const url = process.env.BOOKING_SERVICE_URL;
|
|
const token = process.env.BOOKING_SERVICE_TOKEN;
|
|
if (!url || !token) {
|
|
console.log('Синхронизация: не указаны BOOKING_SERVICE_URL или TOKEN');
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const response = await axios.get(`${url}/api/bookings`, {
|
|
headers: { 'X-API-Key': token }
|
|
});
|
|
const bookings = response.data;
|
|
|
|
const insertStmt = db.prepare(`
|
|
INSERT OR IGNORE INTO bookings (external_id, user_id, name, phone_raw, adults, children, checkin_date, checkout_date, status)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'Новая')
|
|
`);
|
|
const selectUser = db.prepare('SELECT id FROM users WHERE phone = ?');
|
|
const insertUser = db.prepare('INSERT INTO users (phone, name) VALUES (?, ?)');
|
|
|
|
for (const b of bookings) {
|
|
const normPhone = normalizePhone(b.phone);
|
|
let user = selectUser.get(normPhone);
|
|
if (!user) {
|
|
// Создаём карточку клиента
|
|
const info = insertUser.run(normPhone, b.name);
|
|
user = { id: info.lastInsertRowid };
|
|
}
|
|
// Вставляем заявку, если external_id новый
|
|
const result = insertStmt.run(b.id, user.id, b.name, b.phone, b.adults, b.children, b.checkin_date, b.checkout_date);
|
|
if (result.changes > 0) {
|
|
logAction('Новая заявка из внешней системы', { external_id: b.id });
|
|
await notifyNewBooking({...b, external_id: b.id});
|
|
}
|
|
}
|
|
console.log('Синхронизация завершена');
|
|
} catch (err) {
|
|
console.error('Ошибка синхронизации:', err.message);
|
|
}
|
|
}
|
|
|
|
module.exports = { syncBookings }; |