-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
418 lines (362 loc) · 16.8 KB
/
server.js
File metadata and controls
418 lines (362 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
const express = require('express');
const axios = require('axios');
const cheerio = require('cheerio');
const cron = require('node-cron');
const cors = require('cors');
const Anthropic = require('@anthropic-ai/sdk');
const { createClient } = require('@supabase/supabase-js');
const app = express();
app.use(cors());
app.use(express.json());
// ─── Clientes ────────────────────────────────────────────────────────────────
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SECRET_KEY);
// ─── Config desde env vars ───────────────────────────────────────────────────
const TELEGRAM_TOKEN = process.env.TELEGRAM_TOKEN;
const TELEGRAM_CHAT_ID = process.env.TELEGRAM_CHAT_ID;
const SEARCH_INTERVAL = process.env.SEARCH_INTERVAL_HOURS || '12'; // horas
const MAX_PRICE_SOLES = parseInt(process.env.MAX_PRICE_SOLES || '3500');
const MIN_SCORE = parseInt(process.env.MIN_SCORE || '75'); // puntaje IA mínimo para alertar
const TC = parseFloat(process.env.TC || '3.73'); // tipo de cambio referencial
// ─── Filtros de búsqueda ─────────────────────────────────────────────────────
const SEARCH_CONFIG = {
distrito: process.env.SEARCH_DISTRITO || 'san-borja',
distritoLabel: process.env.SEARCH_DISTRITO_LABEL || 'San Borja',
dorms: parseInt(process.env.SEARCH_DORMS || '2'),
maxPriceSoles: MAX_PRICE_SOLES,
maxPriceUSD: Math.round(MAX_PRICE_SOLES / TC)
};
// ─── Utilidades Telegram ─────────────────────────────────────────────────────
async function sendTelegram(message) {
if (!TELEGRAM_TOKEN || !TELEGRAM_CHAT_ID) return;
try {
await axios.post(`https://api.telegram.org/bot${TELEGRAM_TOKEN}/sendMessage`, {
chat_id: TELEGRAM_CHAT_ID,
text: message,
parse_mode: 'HTML'
});
} catch (e) {
console.error('Error Telegram:', e.message);
}
}
// ─── Scrapers ────────────────────────────────────────────────────────────────
// Urbania
async function scrapeUrbania() {
const url = `https://urbania.pe/buscar/alquiler-de-departamentos-en-${SEARCH_CONFIG.distrito}?bedrooms=${SEARCH_CONFIG.dorms}&price_to=${SEARCH_CONFIG.maxPriceUSD}`;
try {
const { data } = await axios.get(url, {
headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' },
timeout: 15000
});
const $ = cheerio.load(data);
const offers = [];
$('[data-qa="posting-card"]').each((i, el) => {
const title = $(el).find('[data-qa="posting-title"]').text().trim();
const price = $(el).find('[data-qa="price"]').text().trim();
const location = $(el).find('[data-qa="posting-location"]').text().trim();
const area = $(el).find('[data-qa="posting-area"]').text().trim();
const link = 'https://urbania.pe' + ($(el).find('a').attr('href') || '');
const rooms = $(el).find('[data-qa="posting-rooms"]').text().trim();
if (title && price) {
offers.push({ title, price, location, area, rooms, link, source: 'Urbania' });
}
});
// Fallback selector alternativo
if (offers.length === 0) {
$('.postingCard').each((i, el) => {
const title = $(el).find('.postingCardTitle').text().trim();
const price = $(el).find('.firstPrice').text().trim();
const location = $(el).find('.postingCardLocation').text().trim();
const link = 'https://urbania.pe' + ($(el).find('a').first().attr('href') || '');
if (title && price) {
offers.push({ title, price, location, area: '', rooms: '', link, source: 'Urbania' });
}
});
}
console.log(`Urbania: ${offers.length} ofertas encontradas`);
return offers.slice(0, 15);
} catch (e) {
console.error('Error scraping Urbania:', e.message);
return [];
}
}
// A Donde Vivir
async function scrapeADondeVivir() {
const url = `https://www.adondevivir.com/propiedades/alquiler/${SEARCH_CONFIG.distrito}?habitaciones=${SEARCH_CONFIG.dorms}&tipocambio=dolares&precioMax=${SEARCH_CONFIG.maxPriceUSD}`;
try {
const { data } = await axios.get(url, {
headers: { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36' },
timeout: 15000
});
const $ = cheerio.load(data);
const offers = [];
$('.aviso-item, .property-card, .listing-item').each((i, el) => {
const title = $(el).find('h2, h3, .title, .aviso-title').first().text().trim();
const price = $(el).find('.precio, .price, .aviso-price').first().text().trim();
const location = $(el).find('.ubicacion, .location, .aviso-location').first().text().trim();
const area = $(el).find('.area, .superficie').first().text().trim();
const href = $(el).find('a').first().attr('href') || '';
const link = href.startsWith('http') ? href : 'https://www.adondevivir.com' + href;
if (title && price) {
offers.push({ title, price, location, area, rooms: `${SEARCH_CONFIG.dorms} dorm.`, link, source: 'A Donde Vivir' });
}
});
console.log(`A Donde Vivir: ${offers.length} ofertas encontradas`);
return offers.slice(0, 15);
} catch (e) {
console.error('Error scraping A Donde Vivir:', e.message);
return [];
}
}
// OLX Perú
async function scrapeOLX() {
const query = encodeURIComponent(`departamento ${SEARCH_CONFIG.distritoLabel} ${SEARCH_CONFIG.dorms} dormitorios`);
const url = `https://www.olx.com.pe/items/q-${query}?search%5Bcategory_id%5D=16`;
try {
const { data } = await axios.get(url, {
headers: { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36' },
timeout: 15000
});
const $ = cheerio.load(data);
const offers = [];
$('[data-aut-id="itemBox"], .IKo3_').each((i, el) => {
const title = $(el).find('[data-aut-id="itemTitle"], ._1KoQO').text().trim();
const price = $(el).find('[data-aut-id="itemPrice"], .fTBQz').text().trim();
const location = $(el).find('[data-aut-id="item-location"], ._1KOFM').text().trim();
const href = $(el).find('a').first().attr('href') || '';
const link = href.startsWith('http') ? href : 'https://www.olx.com.pe' + href;
if (title && price && title.toLowerCase().includes('depart')) {
offers.push({ title, price, location, area: '', rooms: '', link, source: 'OLX Perú' });
}
});
console.log(`OLX: ${offers.length} ofertas encontradas`);
return offers.slice(0, 10);
} catch (e) {
console.error('Error scraping OLX:', e.message);
return [];
}
}
// ─── Puntaje con IA ──────────────────────────────────────────────────────────
async function scoreOffer(offer) {
try {
const prompt = `Eres un experto en el mercado inmobiliario de Lima, Perú.
Analiza esta oferta de departamento en alquiler y devuelve SOLO un JSON con esta estructura exacta:
{
"score": <número 0-100>,
"precio_soles": <número estimado en soles o null si no puedes calcularlo>,
"resumen": "<una línea, máximo 80 caracteres, destacando lo más relevante>",
"ventajas": ["<ventaja 1>", "<ventaja 2>"],
"advertencias": ["<advertencia si aplica>"],
"recomendacion": "buena_oferta" | "regular" | "cara" | "revisar"
}
Contexto de búsqueda:
- Distrito objetivo: ${SEARCH_CONFIG.distritoLabel}
- Dormitorios buscados: ${SEARCH_CONFIG.dorms}
- Presupuesto máximo: S/ ${SEARCH_CONFIG.maxPriceSoles} / mes
- Tipo de cambio referencial: S/ ${TC} por USD
Oferta a analizar:
- Título: ${offer.title}
- Precio publicado: ${offer.price}
- Ubicación: ${offer.location}
- Área: ${offer.area}
- Ambientes: ${offer.rooms}
- Portal: ${offer.source}
Considera: precio por m², proximidad a zonas clave de San Borja, relación precio/calidad vs mercado Lima 2025.
Un score ≥75 es buena oferta. ≥85 es excelente.`;
const response = await anthropic.messages.create({
model: 'claude-haiku-4-5-20251001',
max_tokens: 400,
messages: [{ role: 'user', content: prompt }]
});
const text = response.content[0].text.trim();
const clean = text.replace(/```json|```/g, '').trim();
return JSON.parse(clean);
} catch (e) {
console.error('Error scoring offer:', e.message);
return { score: 50, precio_soles: null, resumen: offer.title, ventajas: [], advertencias: [], recomendacion: 'revisar' };
}
}
// ─── Guardar en Supabase ─────────────────────────────────────────────────────
async function saveOffer(offer, scoring) {
try {
const { data: existing } = await supabase
.from('honicho_offers')
.select('id')
.eq('link', offer.link)
.single();
if (existing) return false; // ya existe
await supabase.from('honicho_offers').insert({
title: offer.title,
price_raw: offer.price,
price_soles: scoring.precio_soles,
location: offer.location,
area: offer.area,
rooms: offer.rooms,
link: offer.link,
source: offer.source,
score: scoring.score,
resumen: scoring.resumen,
ventajas: scoring.ventajas,
advertencias: scoring.advertencias,
recomendacion: scoring.recomendacion,
distrito: SEARCH_CONFIG.distrito,
status: 'active',
found_at: new Date().toISOString()
});
return true;
} catch (e) {
console.error('Error guardando oferta:', e.message);
return false;
}
}
// ─── Alerta Telegram ─────────────────────────────────────────────────────────
function buildTelegramAlert(offer, scoring) {
const emoji = scoring.score >= 85 ? '🔥' : scoring.score >= 75 ? '⭐' : '📌';
const estrellas = scoring.score >= 85 ? '★★★' : scoring.score >= 75 ? '★★☆' : '★☆☆';
let msg = `${emoji} <b>HONICHO — Nueva oferta ${estrellas}</b>\n\n`;
msg += `<b>${offer.title}</b>\n`;
msg += `💰 ${offer.price}`;
if (scoring.precio_soles) msg += ` · S/ ${scoring.precio_soles.toLocaleString('es-PE')}`;
msg += `\n📍 ${offer.location || SEARCH_CONFIG.distritoLabel}\n`;
if (offer.area) msg += `📐 ${offer.area}\n`;
msg += `🏠 ${offer.source} · Score: ${scoring.score}/100\n\n`;
msg += `<i>${scoring.resumen}</i>\n\n`;
if (scoring.ventajas && scoring.ventajas.length > 0) {
msg += `✅ ${scoring.ventajas.slice(0, 2).join('\n✅ ')}\n`;
}
if (scoring.advertencias && scoring.advertencias.length > 0) {
msg += `⚠️ ${scoring.advertencias[0]}\n`;
}
msg += `\n🔗 <a href="${offer.link}">Ver oferta completa</a>`;
return msg;
}
// ─── Ciclo principal de búsqueda ─────────────────────────────────────────────
async function runSearch() {
console.log(`\n[${new Date().toISOString()}] Iniciando búsqueda Honicho...`);
console.log(`Filtros: ${SEARCH_CONFIG.distritoLabel} · ${SEARCH_CONFIG.dorms} dorm · hasta S/ ${SEARCH_CONFIG.maxPriceSoles}`);
// Scraping en paralelo
const [urbania, adv, olx] = await Promise.all([
scrapeUrbania(),
scrapeADondeVivir(),
scrapeOLX()
]);
const allOffers = [...urbania, ...adv, ...olx];
console.log(`Total ofertas scraped: ${allOffers.length}`);
if (allOffers.length === 0) {
console.log('Sin ofertas esta vez. Los portales pueden estar bloqueando temporalmente.');
return;
}
let nuevas = 0;
let alertadas = 0;
for (const offer of allOffers) {
const scoring = await scoreOffer(offer);
const isNew = await saveOffer(offer, scoring);
if (isNew) {
nuevas++;
console.log(`Nueva oferta: ${offer.title} | Score: ${scoring.score} | ${offer.source}`);
if (scoring.score >= MIN_SCORE) {
alertadas++;
const msg = buildTelegramAlert(offer, scoring);
await sendTelegram(msg);
await new Promise(r => setTimeout(r, 1000)); // evitar flood
}
}
}
console.log(`Búsqueda completada: ${nuevas} nuevas, ${alertadas} alertadas por Telegram`);
if (nuevas > 0) {
await sendTelegram(
`🏠 <b>Honicho</b> — Ciclo completado\n` +
`📊 ${allOffers.length} revisadas · ${nuevas} nuevas · ${alertadas} buenas ofertas alertadas\n` +
`🕐 ${new Date().toLocaleString('es-PE', { timeZone: 'America/Lima' })}`
);
}
}
// ─── Endpoints API ────────────────────────────────────────────────────────────
// Ofertas activas
app.get('/api/offers', async (req, res) => {
try {
const { distrito, min_score, limit } = req.query;
let query = supabase
.from('honicho_offers')
.select('*')
.eq('status', 'active')
.order('score', { ascending: false })
.limit(parseInt(limit) || 50);
if (distrito) query = query.eq('distrito', distrito);
if (min_score) query = query.gte('score', parseInt(min_score));
const { data, error } = await query;
if (error) throw error;
res.json({ offers: data || [], total: data?.length || 0 });
} catch (e) {
res.status(500).json({ error: e.message });
}
});
// Marcar oferta como vista/descartada
app.patch('/api/offers/:id', async (req, res) => {
try {
const { status } = req.body;
const { data, error } = await supabase
.from('honicho_offers')
.update({ status })
.eq('id', req.params.id)
.select()
.single();
if (error) throw error;
res.json(data);
} catch (e) {
res.status(500).json({ error: e.message });
}
});
// Búsqueda manual desde el panel
app.post('/api/search/run', async (req, res) => {
res.json({ message: 'Búsqueda iniciada en segundo plano' });
runSearch().catch(console.error);
});
// Stats
app.get('/api/stats', async (req, res) => {
try {
const { data: total } = await supabase.from('honicho_offers').select('id', { count: 'exact' }).eq('status', 'active');
const { data: buenas } = await supabase.from('honicho_offers').select('id', { count: 'exact' }).gte('score', 75).eq('status', 'active');
const { data: latest } = await supabase.from('honicho_offers').select('found_at').order('found_at', { ascending: false }).limit(1);
res.json({
total_activas: total?.length || 0,
buenas_ofertas: buenas?.length || 0,
ultima_busqueda: latest?.[0]?.found_at || null,
config: SEARCH_CONFIG
});
} catch (e) {
res.status(500).json({ error: e.message });
}
});
// Health check
app.get('/api/health', (req, res) => {
res.json({ status: 'ok', service: 'Honicho Backend', time: new Date().toISOString() });
});
// IP pública (útil para debug)
app.get('/api/myip', async (req, res) => {
try {
const { data } = await axios.get('https://api.ipify.org?format=json');
res.json(data);
} catch (e) {
res.json({ ip: 'unknown' });
}
});
// ─── Cron: cada 12 horas ─────────────────────────────────────────────────────
const cronExpression = SEARCH_INTERVAL === '6' ? '0 */6 * * *'
: SEARCH_INTERVAL === '12' ? '0 */12 * * *'
: '0 8 * * *'; // default: 1 vez al día a las 8am
cron.schedule(cronExpression, () => {
runSearch().catch(console.error);
}, { timezone: 'America/Lima' });
// ─── Arranque ─────────────────────────────────────────────────────────────────
const PORT = process.env.PORT || 3000;
app.listen(PORT, async () => {
console.log(`\n🏠 Honicho Backend corriendo en puerto ${PORT}`);
console.log(`📍 Buscando en: ${SEARCH_CONFIG.distritoLabel} · ${SEARCH_CONFIG.dorms} dorm · hasta S/ ${SEARCH_CONFIG.maxPriceSoles}`);
console.log(`⏰ Intervalo: cada ${SEARCH_INTERVAL} horas`);
console.log(`🔔 Puntaje mínimo para alertar: ${MIN_SCORE}/100`);
// Primera búsqueda al arrancar (con delay para que Railway esté listo)
setTimeout(() => {
runSearch().catch(console.error);
}, 5000);
});