feat: captura y respaldo de login clasico, screenshots para tiendas y servicios sinpe
This commit is contained in:
@@ -0,0 +1,189 @@
|
||||
/**
|
||||
* Servicio de Lectura y Conciliación IMAP de Notificaciones SINPE Móvil para SiboPay
|
||||
*/
|
||||
|
||||
const imapSimple = require('imap-simple');
|
||||
const { simpleParser } = require('mailparser');
|
||||
const { parseSinpeEmail, normalizarCodigoDetalle } = require('./sinpeParser');
|
||||
|
||||
let isChecking = false;
|
||||
|
||||
const getImapConfig = () => {
|
||||
const cleanPassword = (process.env.SINPE_EMAIL_PASSWORD || '').replace(/\s+/g, '');
|
||||
return {
|
||||
imap: {
|
||||
user: process.env.SINPE_EMAIL_USER || '',
|
||||
password: cleanPassword,
|
||||
host: process.env.SINPE_IMAP_HOST || 'imap.gmail.com',
|
||||
port: parseInt(process.env.SINPE_IMAP_PORT || '993', 10),
|
||||
tls: true,
|
||||
authTimeout: 10000,
|
||||
tlsOptions: { rejectUnauthorized: false }
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Escanea la bandeja de entrada buscando los correos más recientes de notificación SINPE
|
||||
* y los guarda en la base de datos de transacciones.
|
||||
*/
|
||||
async function checkSinpeEmailsOnce(db) {
|
||||
if (isChecking) return { scanned: 0, status: 'already_running' };
|
||||
|
||||
const user = process.env.SINPE_EMAIL_USER;
|
||||
const pass = process.env.SINPE_EMAIL_PASSWORD;
|
||||
const isEnabled = process.env.SINPE_IMAP_ENABLED === 'true' || process.env.SINPE_IMAP_ENABLED === '1';
|
||||
|
||||
if (!isEnabled || !user || !pass) {
|
||||
return { scanned: 0, status: 'disabled_or_unconfigured' };
|
||||
}
|
||||
|
||||
isChecking = true;
|
||||
let connection = null;
|
||||
let savedCount = 0;
|
||||
|
||||
try {
|
||||
const config = getImapConfig();
|
||||
connection = await imapSimple.connect(config);
|
||||
const box = await connection.openBox('INBOX');
|
||||
|
||||
const totalMessages = (box && box.messages && box.messages.total) || 0;
|
||||
if (totalMessages === 0) {
|
||||
return { scanned: 0, status: 'empty_inbox' };
|
||||
}
|
||||
|
||||
// Consultar los últimos 25 correos
|
||||
const startSeq = Math.max(1, totalMessages - 24);
|
||||
const searchCriteria = [`${startSeq}:${totalMessages}`];
|
||||
const fetchOptions = {
|
||||
bodies: ['HEADER', 'TEXT', ''],
|
||||
markSeen: false,
|
||||
struct: true
|
||||
};
|
||||
|
||||
const messages = await connection.search(searchCriteria, fetchOptions);
|
||||
|
||||
if (messages && messages.length > 0) {
|
||||
for (const msg of messages) {
|
||||
try {
|
||||
const headerPart = msg.parts.find(p => p.which === 'HEADER');
|
||||
const rawHeader = headerPart ? headerPart.body : {};
|
||||
let subject = Array.isArray(rawHeader.subject) ? rawHeader.subject[0] : (rawHeader.subject || '');
|
||||
let from = Array.isArray(rawHeader.from) ? rawHeader.from[0] : (rawHeader.from || '');
|
||||
|
||||
const allPart = msg.parts.find(p => p.which === '' || p.which === 'TEXT');
|
||||
let bodyText = '';
|
||||
let bodyHtml = '';
|
||||
|
||||
if (allPart && allPart.body) {
|
||||
const parsed = await simpleParser(allPart.body);
|
||||
bodyText = parsed.text || '';
|
||||
bodyHtml = parsed.html || '';
|
||||
if (parsed.subject) subject = parsed.subject;
|
||||
if (parsed.from && parsed.from.text) from = parsed.from.text;
|
||||
}
|
||||
|
||||
const parsedSinpe = parseSinpeEmail(subject, bodyText, bodyHtml, from);
|
||||
|
||||
if (parsedSinpe.isSinpe && parsedSinpe.amountCrc > 0) {
|
||||
const txId = `sinpe_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`;
|
||||
const normCod = parsedSinpe.codigoDetalleNormalizado || '';
|
||||
const refNum = parsedSinpe.referenceNumber || (normCod ? `REF-${normCod}` : `TX-${Date.now()}`);
|
||||
|
||||
// Insertar o ignorar si ya existe
|
||||
try {
|
||||
if (db) {
|
||||
const existing = db.prepare(`
|
||||
SELECT id FROM sinpe_transacciones_banco
|
||||
WHERE (codigo_detalle_norm = ? AND codigo_detalle_norm IS NOT NULL AND codigo_detalle_norm != '')
|
||||
OR (reference_number = ? AND reference_number IS NOT NULL AND reference_number != '')
|
||||
LIMIT 1
|
||||
`).get(normCod || '__none__', refNum);
|
||||
|
||||
if (!existing) {
|
||||
db.prepare(`
|
||||
INSERT INTO sinpe_transacciones_banco
|
||||
(id, reference_number, codigo_detalle, codigo_detalle_norm, amount_crc, sender_phone, sender_name, origin_bank, status, raw_data)
|
||||
VALUES
|
||||
(?, ?, ?, ?, ?, ?, ?, ?, 'unclaimed', ?)
|
||||
`).run(
|
||||
txId,
|
||||
refNum,
|
||||
parsedSinpe.codigoDetalle || null,
|
||||
normCod || null,
|
||||
parsedSinpe.amountCrc,
|
||||
parsedSinpe.senderPhone || null,
|
||||
parsedSinpe.senderName || 'Cliente SINPE',
|
||||
parsedSinpe.originBank || 'SINPE Móvil',
|
||||
JSON.stringify({ from, subject, summary: parsedSinpe.rawSummary })
|
||||
);
|
||||
savedCount++;
|
||||
console.log(`💵 [SINPE IMAP] Notificación registrada: ₡${parsedSinpe.amountCrc} | Código: ${parsedSinpe.codigoDetalle || 'N/A'} | Ref: #${refNum} | Banco: ${parsedSinpe.originBank}`);
|
||||
}
|
||||
}
|
||||
} catch (dbErr) {
|
||||
console.warn('⚠️ [SINPE IMAP] Error al persistir en BD:', dbErr.message);
|
||||
}
|
||||
}
|
||||
} catch (msgErr) {
|
||||
console.warn('⚠️ [SINPE IMAP] Error procesando correo:', msgErr.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { scanned: messages ? messages.length : 0, saved: savedCount, status: 'ok' };
|
||||
} catch (err) {
|
||||
console.error('❌ [SINPE IMAP] Error de conexión:', err.message);
|
||||
return { scanned: 0, status: 'error', error: err.message };
|
||||
} finally {
|
||||
if (connection) {
|
||||
try { connection.end(); } catch (_) {}
|
||||
}
|
||||
isChecking = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserta manualmente una transacción simulada (útil para pruebas inmediatas en QA o sin transferir dinero real)
|
||||
*/
|
||||
function simularSinpeEmail(db, { codigo, codigoDetalle, monto, banco, remitente, telefono, comprobante }) {
|
||||
if (!db) throw new Error('DB no inicializada');
|
||||
const txId = `sim_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`;
|
||||
const rawCod = codigo || codigoDetalle || null;
|
||||
const cleanCod = rawCod ? String(rawCod).trim() : null;
|
||||
const normCod = cleanCod ? normalizarCodigoDetalle(cleanCod) : null;
|
||||
const refNum = comprobante ? String(comprobante).trim() : (normCod ? `REF-${normCod}` : `SIM-${Date.now()}`);
|
||||
const montoNum = parseInt(monto, 10) || 1000;
|
||||
|
||||
db.prepare(`
|
||||
INSERT INTO sinpe_transacciones_banco
|
||||
(id, reference_number, codigo_detalle, codigo_detalle_norm, amount_crc, sender_phone, sender_name, origin_bank, status, raw_data)
|
||||
VALUES
|
||||
(?, ?, ?, ?, ?, ?, ?, ?, 'unclaimed', ?)
|
||||
`).run(
|
||||
txId,
|
||||
refNum,
|
||||
cleanCod,
|
||||
normCod,
|
||||
montoNum,
|
||||
telefono || '8888-1122',
|
||||
remitente || 'Padre de Familia',
|
||||
banco || 'BAC Credomatic',
|
||||
JSON.stringify({ simulado: true, fecha: new Date().toISOString() })
|
||||
);
|
||||
|
||||
return {
|
||||
id: txId,
|
||||
codigo_detalle: cleanCod,
|
||||
codigo_detalle_norm: normCod,
|
||||
reference_number: refNum,
|
||||
amount_crc: montoNum,
|
||||
origin_bank: banco || 'BAC Credomatic',
|
||||
sender_name: remitente || 'Padre de Familia'
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
checkSinpeEmailsOnce,
|
||||
simularSinpeEmail
|
||||
};
|
||||
@@ -0,0 +1,184 @@
|
||||
/**
|
||||
* Parser de Notificaciones Bancarias de SINPE Móvil (Costa Rica) para SiboPay
|
||||
* Extrae:
|
||||
* - Códigos de detalle SiboPay (SIBO-XXXX o SIBOXXXX) con tolerancia total a guiones/espacios/mayúsculas
|
||||
* - Montos en colones (₡ / CRC)
|
||||
* - Números de comprobante / referencia bancaria
|
||||
* - Banco de origen (BAC, BCR, BNCR, Promerica, Davivienda, Scotiabank, etc.)
|
||||
* - Teléfono y nombre del remitente
|
||||
*/
|
||||
|
||||
function stripHtml(html = '') {
|
||||
return String(html)
|
||||
.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
|
||||
.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
|
||||
.replace(/<[^>]+>/g, ' ')
|
||||
.replace(/ /gi, ' ')
|
||||
.replace(/&/gi, '&')
|
||||
.replace(/</gi, '<')
|
||||
.replace(/>/gi, '>')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Normaliza un código de SINPE para comparación tolerante
|
||||
* Ejemplos: "SIBO-7K9M", "sibo7k9m", "SIBO 7k9m", "sibo-7k9m" -> "SIBO7K9M"
|
||||
*/
|
||||
function normalizarCodigoDetalle(codigo = '') {
|
||||
if (!codigo) return '';
|
||||
const str = String(codigo).trim();
|
||||
const match = str.match(/\bSIBO[\s\-_]?([A-Za-z0-9]{3,8})\b/i) || str.match(/SIBO[\s\-_]?([A-Za-z0-9]{3,8})/i);
|
||||
if (match) {
|
||||
return `SIBO${match[1].toUpperCase()}`;
|
||||
}
|
||||
return str.replace(/[\s\-_]/g, '').toUpperCase();
|
||||
}
|
||||
|
||||
function parseSinpeEmail(arg1 = '', bodyText = '', bodyHtml = '', from = '') {
|
||||
let subject = '';
|
||||
let text = '';
|
||||
let html = '';
|
||||
let cleanFrom = '';
|
||||
|
||||
if (typeof arg1 === 'object' && arg1 !== null) {
|
||||
subject = arg1.subject || '';
|
||||
text = arg1.text || arg1.bodyText || '';
|
||||
html = arg1.html || arg1.bodyHtml || '';
|
||||
cleanFrom = String(arg1.from || '').toLowerCase();
|
||||
} else {
|
||||
subject = String(arg1 || '');
|
||||
text = String(bodyText || '');
|
||||
html = String(bodyHtml || '');
|
||||
cleanFrom = String(from || '').toLowerCase();
|
||||
}
|
||||
|
||||
const fullText = `${subject}\n${text}\n${stripHtml(html)}`.trim();
|
||||
const lowerText = fullText.toLowerCase();
|
||||
|
||||
// 1. Detección de Banco de Costa Rica
|
||||
let originBank = 'SINPE Móvil CR';
|
||||
if (cleanFrom.includes('bac') || lowerText.includes('bac credomatic') || lowerText.includes('bac san jose')) {
|
||||
originBank = 'BAC Credomatic';
|
||||
} else if (cleanFrom.includes('bncr') || lowerText.includes('banco nacional') || lowerText.includes('bn móvil') || lowerText.includes('bn movil')) {
|
||||
originBank = 'Banco Nacional (BNCR)';
|
||||
} else if (cleanFrom.includes('bancobcr') || cleanFrom.includes('bcr') || lowerText.includes('banco de costa rica')) {
|
||||
originBank = 'Banco de Costa Rica (BCR)';
|
||||
} else if (cleanFrom.includes('promerica') || lowerText.includes('promerica')) {
|
||||
originBank = 'Banco Promerica';
|
||||
} else if (cleanFrom.includes('scotiabank') || lowerText.includes('scotiabank')) {
|
||||
originBank = 'Scotiabank';
|
||||
} else if (cleanFrom.includes('davivienda') || lowerText.includes('davivienda')) {
|
||||
originBank = 'Davivienda';
|
||||
} else if (cleanFrom.includes('wink') || cleanFrom.includes('coopenae') || lowerText.includes('wink')) {
|
||||
originBank = 'Wink (Coopenae)';
|
||||
} else if (cleanFrom.includes('sibopay') || cleanFrom.includes('simulad')) {
|
||||
originBank = 'SiboPay Direct';
|
||||
}
|
||||
|
||||
// 2. Extraer Código de Detalle SiboPay (Tolerancia total a guión, espacios o todo pegado)
|
||||
let codigoDetalle = null;
|
||||
const codigoRegex = /\bSIBO[\s\-_]?([A-Za-z0-9]{3,8})\b/i;
|
||||
const matchCodigo = fullText.match(codigoRegex) || fullText.match(/SIBO[\s\-_]?([A-Za-z0-9]{3,8})/i);
|
||||
if (matchCodigo) {
|
||||
codigoDetalle = `SIBO-${matchCodigo[1].toUpperCase()}`;
|
||||
}
|
||||
|
||||
// 3. Extraer Monto en Colones (₡ / CRC / ¢)
|
||||
let amountCrc = 0;
|
||||
const amountPatterns = [
|
||||
/(?:monto|importe|valor|suma|por concepto de|total|cr[eé]dito|acreditad[oa]|recibid[oa]|transferid[oa])\s*(?:de|por)?\s*[:#=\-]?\s*(?:₡|¢|CRC)?\s*([0-9]+(?:[,.\s][0-9]+)*)\s*(?:colones|crc|¢|₡)?/i,
|
||||
/(?:₡|¢|CRC)\s*[:#=\-]?\s*([0-9]+(?:[,.\s][0-9]+)*)/i,
|
||||
/([0-9]+(?:[,.\s][0-9]+)*)\s*(?:colones|crc|¢|₡)/i,
|
||||
/(?:crc|colones)\s*[:#=\-]?\s*([0-9]+(?:[,.\s][0-9]+)*)/i
|
||||
];
|
||||
|
||||
for (const regex of amountPatterns) {
|
||||
const match = fullText.match(regex);
|
||||
if (match && match[1]) {
|
||||
let numStr = match[1].trim().replace(/\s+/g, '');
|
||||
if (numStr.includes('.') && numStr.includes(',')) {
|
||||
if (numStr.indexOf('.') < numStr.indexOf(',')) {
|
||||
numStr = numStr.replace(/\./g, '').replace(',', '.');
|
||||
} else {
|
||||
numStr = numStr.replace(/,/g, '');
|
||||
}
|
||||
} else if (numStr.includes(',')) {
|
||||
const parts = numStr.split(',');
|
||||
if (parts[1] && parts[1].length === 2) {
|
||||
numStr = parts[0] + '.' + parts[1];
|
||||
} else {
|
||||
numStr = numStr.replace(/,/g, '');
|
||||
}
|
||||
}
|
||||
const parsedNum = parseFloat(numStr);
|
||||
if (!isNaN(parsedNum) && parsedNum > 0) {
|
||||
amountCrc = Math.round(parsedNum);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Extraer Teléfono Emisor (8 dígitos)
|
||||
let senderPhone = null;
|
||||
const phonePatterns = [
|
||||
/(?:tel[eé]fono|origen|celular|m[oó]vil|remitente|emisor)\s*[:#=\-]?\s*(?:\+?506\s*[-.]?)?([245678]\d{3}[-\s.]?\d{4})/i,
|
||||
/(?:\+?506\s*[-.]?)?([245678]\d{3}[-\s.]?\d{4})/i
|
||||
];
|
||||
for (const regex of phonePatterns) {
|
||||
const match = fullText.match(regex);
|
||||
if (match && match[1]) {
|
||||
const digits = match[1].replace(/\D/g, '');
|
||||
if (digits.length === 8) {
|
||||
senderPhone = `${digits.slice(0, 4)}-${digits.slice(4)}`;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Extraer Número de Comprobante / Referencia Bancaria
|
||||
let referenceNumber = null;
|
||||
const refPatterns = [
|
||||
/(?:n[uú]mero\s*(?:de\s*)?|n[o°º]\.?\s*(?:de\s*)?|c[oó]digo\s*(?:de\s*)?)?(?:comprobante|referencia|transacci[oó]n|autorizaci[oó]n|operaci[oó]n|documento|folio|confirmaci[oó]n|trf|ref|doc|aut)(?:\s+de\s+(?:transferencia|pago|operaci[oó]n|dep[oó]sito|transacci[oó]n))?\s*[:#=\.\-]?\s*([A-Za-z0-9\-_]{4,35})/i,
|
||||
/#\s*([A-Za-z0-9\-_]{4,24})/,
|
||||
/(?:SINPE|TRF|DOC|REF|AUT)[-_]?([0-9]{4,20})/i
|
||||
];
|
||||
for (const regex of refPatterns) {
|
||||
const match = fullText.match(regex);
|
||||
if (match && match[1]) {
|
||||
const clean = match[1].trim();
|
||||
if (!clean.toUpperCase().startsWith('SIBO') && clean.length >= 4) {
|
||||
referenceNumber = clean;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Nombre del remitente si está disponible
|
||||
let senderName = null;
|
||||
const nameMatch = fullText.match(/(?:de|de parte de|remitente|ordenante|cliente|titular)\s*[:#=\-]?\s*([A-Za-zÀ-ÿ\s]{4,40})(?:\n|\r|\.|,|-)/i);
|
||||
if (nameMatch && nameMatch[1]) {
|
||||
const cand = nameMatch[1].trim();
|
||||
if (!cand.toLowerCase().includes('banco') && !cand.toLowerCase().includes('sinpe')) {
|
||||
senderName = cand;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isSinpe: Boolean(amountCrc > 0 && (codigoDetalle || referenceNumber || originBank !== 'SINPE Móvil CR')),
|
||||
codigoDetalle,
|
||||
codigoDetalleNormalizado: codigoDetalle ? normalizarCodigoDetalle(codigoDetalle) : null,
|
||||
amount: amountCrc,
|
||||
amountCrc,
|
||||
referenceNumber: referenceNumber || (codigoDetalle ? `REF-${codigoDetalle.replace(/[^A-Za-z0-9]/g, '')}` : null),
|
||||
senderPhone: senderPhone || '',
|
||||
senderName: senderName || 'Cliente SINPE',
|
||||
originBank,
|
||||
rawSummary: subject || ''
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
parseSinpeEmail,
|
||||
normalizarCodigoDetalle
|
||||
};
|
||||
Reference in New Issue
Block a user