horapi / server.js
ShieldX's picture
Upload 5 files
33564cc verified
const express = require('express');
const cors = require('cors');
const { db } = require('./src/firebase');
const axios = require('axios'); // Import axios
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 7860;
app.use(cors());
app.use(express.json());
// --- HELPER: Telegram Notification ---
const sendTelegramAlert = async (data) => {
const token = process.env.TELEGRAM_BOT_TOKEN;
const chatId = process.env.TELEGRAM_CHAT_ID;
if (!token || !chatId) {
console.warn("⚠️ Telegram credentials missing in .env");
return;
}
// Format the message nicely
const message = `
πŸ”” *New Lead: House of Ruqa*
πŸ‘€ *Name:* ${data.name}
πŸ“§ *Email:* ${data.email}
πŸ“ž *Phone:* ${data.phone}
πŸ“¦ *Package:* ${data.packageType}
πŸ“ *Message:*
${data.message}
`;
try {
const url = `https://api.telegram.org/bot${token}/sendMessage`;
await axios.post(url, {
chat_id: chatId,
text: message,
parse_mode: 'Markdown' // Allows bolding
});
console.log("✈️ Telegram Notification Sent");
} catch (error) {
console.error("❌ Telegram Error:", error.response ? error.response.data : error.message);
}
};
// --- ROUTES ---
app.get('/health', (req, res) => {
res.status(200).json({ status: 'Online', system: 'House of Ruqa Backend' });
});
app.post('/api/lead', async (req, res) => {
try {
const { name, email, phone, message, packageType } = req.body;
if (!name || !email) {
return res.status(400).json({ error: 'Name and Email are required.' });
}
const leadData = {
name,
email,
phone: phone || 'N/A',
message: message || '',
packageType: packageType || 'General Inquiry',
timestamp: new Date().toISOString(),
status: 'new',
source: 'website_form'
};
// 1. Save to Firebase
const docRef = await db.collection('leads').add(leadData);
console.log(`βœ… New Lead Saved: ${docRef.id}`);
// 2. Send Telegram Alert (Async - don't wait for it to respond to user)
sendTelegramAlert(leadData);
res.status(201).json({
success: true,
message: 'Request received.',
id: docRef.id
});
} catch (error) {
console.error("❌ Error processing lead:", error);
res.status(500).json({ success: false, error: 'Internal Server Error' });
}
});
app.listen(PORT, () => {
console.log(`πŸ‘‘ House of Ruqa Server running on port ${PORT}`);
});