feat: Integrar PostgreSQL en VPS para RecreoPay con soporte en pgAdmin y retener compatibilidad local
This commit is contained in:
Generated
+176
-1
@@ -13,7 +13,21 @@
|
|||||||
"cors": "^2.8.6",
|
"cors": "^2.8.6",
|
||||||
"express": "^5.2.1",
|
"express": "^5.2.1",
|
||||||
"jsqr": "^1.4.0",
|
"jsqr": "^1.4.0",
|
||||||
"qrcode": "^1.5.4"
|
"pg": "^8.23.1",
|
||||||
|
"qrcode": "^1.5.4",
|
||||||
|
"synckit": "^0.11.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@pkgr/core": {
|
||||||
|
"version": "0.3.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.3.6.tgz",
|
||||||
|
"integrity": "sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": "^14.18.0 || >=16.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/pkgr"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/accepts": {
|
"node_modules/accepts": {
|
||||||
@@ -835,6 +849,95 @@
|
|||||||
"url": "https://opencollective.com/express"
|
"url": "https://opencollective.com/express"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/pg": {
|
||||||
|
"version": "8.23.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg/-/pg-8.23.1.tgz",
|
||||||
|
"integrity": "sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"pg-connection-string": "^2.14.1",
|
||||||
|
"pg-pool": "^3.14.0",
|
||||||
|
"pg-protocol": "^1.16.1",
|
||||||
|
"pg-types": "2.2.0",
|
||||||
|
"pgpass": "1.0.5"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 16.0.0"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"pg-cloudflare": "^1.4.1"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"pg-native": ">=3.0.1"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"pg-native": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/pg-cloudflare": {
|
||||||
|
"version": "1.4.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.1.tgz",
|
||||||
|
"integrity": "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"node_modules/pg-connection-string": {
|
||||||
|
"version": "2.14.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz",
|
||||||
|
"integrity": "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/pg-int8": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
|
||||||
|
"license": "ISC",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/pg-pool": {
|
||||||
|
"version": "3.14.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz",
|
||||||
|
"integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"peerDependencies": {
|
||||||
|
"pg": ">=8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/pg-protocol": {
|
||||||
|
"version": "1.16.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.1.tgz",
|
||||||
|
"integrity": "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/pg-types": {
|
||||||
|
"version": "2.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
|
||||||
|
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"pg-int8": "1.0.1",
|
||||||
|
"postgres-array": "~2.0.0",
|
||||||
|
"postgres-bytea": "~1.0.0",
|
||||||
|
"postgres-date": "~1.0.4",
|
||||||
|
"postgres-interval": "^1.1.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/pgpass": {
|
||||||
|
"version": "1.0.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
|
||||||
|
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"split2": "^4.1.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/pngjs": {
|
"node_modules/pngjs": {
|
||||||
"version": "5.0.0",
|
"version": "5.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",
|
||||||
@@ -844,6 +947,45 @@
|
|||||||
"node": ">=10.13.0"
|
"node": ">=10.13.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/postgres-array": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/postgres-bytea": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/postgres-date": {
|
||||||
|
"version": "1.0.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
|
||||||
|
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/postgres-interval": {
|
||||||
|
"version": "1.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
|
||||||
|
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"xtend": "^4.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/proxy-addr": {
|
"node_modules/proxy-addr": {
|
||||||
"version": "2.0.8",
|
"version": "2.0.8",
|
||||||
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz",
|
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz",
|
||||||
@@ -1088,6 +1230,15 @@
|
|||||||
"url": "https://github.com/sponsors/ljharb"
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/split2": {
|
||||||
|
"version": "4.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
|
||||||
|
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
|
||||||
|
"license": "ISC",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10.x"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/statuses": {
|
"node_modules/statuses": {
|
||||||
"version": "2.0.2",
|
"version": "2.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
|
||||||
@@ -1123,6 +1274,21 @@
|
|||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/synckit": {
|
||||||
|
"version": "0.11.13",
|
||||||
|
"resolved": "https://registry.npmjs.org/synckit/-/synckit-0.11.13.tgz",
|
||||||
|
"integrity": "sha512-eNRKgb3z66Yp3D2CixVujOUvXLFUTij/zVnV8KRyvFdQwpz7I5DS8UfRkTeLzb64u+dkzDSdelE24izu+zSSUg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@pkgr/core": "^0.3.6"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^14.18.0 || >=16.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/synckit"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/toidentifier": {
|
"node_modules/toidentifier": {
|
||||||
"version": "1.0.1",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
|
||||||
@@ -1207,6 +1373,15 @@
|
|||||||
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
|
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
|
"node_modules/xtend": {
|
||||||
|
"version": "4.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
|
||||||
|
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/y18n": {
|
"node_modules/y18n": {
|
||||||
"version": "4.0.3",
|
"version": "4.0.3",
|
||||||
"resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz",
|
"resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz",
|
||||||
|
|||||||
+3
-1
@@ -25,6 +25,8 @@
|
|||||||
"cors": "^2.8.6",
|
"cors": "^2.8.6",
|
||||||
"express": "^5.2.1",
|
"express": "^5.2.1",
|
||||||
"jsqr": "^1.4.0",
|
"jsqr": "^1.4.0",
|
||||||
"qrcode": "^1.5.4"
|
"pg": "^8.23.1",
|
||||||
|
"qrcode": "^1.5.4",
|
||||||
|
"synckit": "^0.11.13"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
const Database = require('better-sqlite3');
|
||||||
|
const { Client } = require('pg');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const sqlitePath = path.join(__dirname, '..', 'server', 'recreopay.db');
|
||||||
|
const dbSqlite = new Database(sqlitePath);
|
||||||
|
|
||||||
|
const pgUrl = process.env.DATABASE_URL || 'postgresql://postgres:[email protected]:5432/recreopay_db';
|
||||||
|
const client = new Client({ connectionString: pgUrl });
|
||||||
|
|
||||||
|
async function migrate() {
|
||||||
|
console.log('🚀 Conectando a PostgreSQL:', pgUrl);
|
||||||
|
await client.connect();
|
||||||
|
|
||||||
|
const tables = [
|
||||||
|
{ name: 'usuarios', cols: ['id', 'username', 'password_hash', 'rol', 'nombre', 'telefono', 'email', 'activo', 'creado_en'] },
|
||||||
|
{ name: 'estudiantes', cols: ['id', 'usuario_id', 'codigo_estudiante', 'nombre_completo', 'edad', 'grado', 'seccion', 'qr_token', 'pin_seguridad', 'foto_url', 'saldo_colones', 'limite_diario_colones', 'alergias', 'bloquear_chucherias', 'tarjeta_bloqueada', 'padre_nombre', 'padre_telefono', 'padre_usuario_id', 'permitir_transferencias', 'activo', 'creado_en'] },
|
||||||
|
{ name: 'categorias', cols: ['id', 'nombre', 'icono', 'orden'] },
|
||||||
|
{ name: 'productos', cols: ['id', 'categoria_id', 'nombre', 'descripcion', 'precio_colones', 'imagen_url', 'stock', 'es_saludable', 'contiene_alergenos', 'disponible', 'icono', 'calorias', 'cumple_mep', 'alergenos', 'permite_preorden', 'destacado', 'control_stock', 'creado_en'] },
|
||||||
|
{ name: 'disenos_tarjetas', cols: ['id', 'theme_id', 'nombre', 'categoria', 'imagen_url', 'estilo_texto', 'es_predeterminado', 'activo', 'creado_en'] },
|
||||||
|
{ name: 'ordenes', cols: ['id', 'codigo_orden', 'estudiante_id', 'tipo_orden', 'momento_entrega', 'estado', 'total_colones', 'notas', 'creado_en', 'entregado_en', 'cajero_id', 'saldo_anterior', 'saldo_posterior', 'metodo_pago', 'observaciones'] },
|
||||||
|
{ name: 'orden_detalles', cols: ['id', 'orden_id', 'producto_id', 'cantidad', 'precio_unitario', 'subtotal', 'nombre_producto'] },
|
||||||
|
{ name: 'transacciones_saldo', cols: ['id', 'estudiante_id', 'tipo', 'monto_colones', 'saldo_previo', 'saldo_posterior', 'comprobante_sinpe', 'orden_id', 'descripcion', 'revertida', 'revertido_por_usuario_id', 'revertido_en', 'fecha'] },
|
||||||
|
{ name: 'padres_estudiantes', cols: ['id', 'padre_usuario_id', 'estudiante_id', 'creado_en'] },
|
||||||
|
{ name: 'notificaciones', cols: ['id', 'usuario_id', 'estudiante_id', 'titulo', 'mensaje', 'tipo', 'leida', 'creado_en'] }
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const t of tables) {
|
||||||
|
try {
|
||||||
|
// Check if table exists in SQLite
|
||||||
|
const existsInSqlite = dbSqlite.prepare(`SELECT count(*) as c FROM sqlite_master WHERE type='table' AND name=?`).get(t.name);
|
||||||
|
if (!existsInSqlite || existsInSqlite.c === 0) {
|
||||||
|
console.log(`⚠️ Tabla "${t.name}" no encontrada en SQLite, omitiendo.`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check which columns exist in SQLite
|
||||||
|
const tableInfo = dbSqlite.prepare(`PRAGMA table_info(${t.name})`).all();
|
||||||
|
const sqliteCols = tableInfo.map(c => c.name);
|
||||||
|
const availableCols = t.cols.filter(c => sqliteCols.includes(c));
|
||||||
|
|
||||||
|
const rows = dbSqlite.prepare(`SELECT ${availableCols.join(', ')} FROM ${t.name}`).all();
|
||||||
|
console.log(`📦 Migrando ${rows.length} registros para la tabla "${t.name}"...`);
|
||||||
|
|
||||||
|
for (const row of rows) {
|
||||||
|
const colsList = availableCols.join(', ');
|
||||||
|
const placeholders = availableCols.map((_, idx) => `$${idx + 1}`).join(', ');
|
||||||
|
const values = availableCols.map(c => row[c]);
|
||||||
|
|
||||||
|
const insertSql = `
|
||||||
|
INSERT INTO ${t.name} (${colsList})
|
||||||
|
VALUES (${placeholders})
|
||||||
|
ON CONFLICT (id) DO NOTHING;
|
||||||
|
`;
|
||||||
|
await client.query(insertSql, values);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sync sequence
|
||||||
|
await client.query(`SELECT setval(pg_get_serial_sequence('${t.name}', 'id'), COALESCE((SELECT MAX(id) FROM ${t.name}), 1));`);
|
||||||
|
console.log(`✅ Tabla "${t.name}" migrada y secuencia actualizada.`);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`❌ Error en tabla "${t.name}":`, err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('\n🎉 ¡Migración de datos a PostgreSQL completada con éxito!');
|
||||||
|
await client.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
migrate().catch(e => {
|
||||||
|
console.error('Fatal error en migración:', e);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
+103
-8
@@ -1,15 +1,108 @@
|
|||||||
const Database = require('better-sqlite3');
|
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
|
|
||||||
const dbPath = path.join(__dirname, 'recreopay.db');
|
try {
|
||||||
const db = new Database(dbPath);
|
const envPath = path.join(__dirname, '../.env');
|
||||||
|
if (fs.existsSync(envPath)) process.loadEnvFile(envPath);
|
||||||
|
} catch (e) {}
|
||||||
|
|
||||||
// Enable WAL mode for high concurrent read/write performance
|
let db;
|
||||||
db.pragma('journal_mode = WAL');
|
const isPg = Boolean(process.env.DATABASE_URL);
|
||||||
db.pragma('foreign_keys = ON');
|
|
||||||
|
if (isPg) {
|
||||||
|
const { createSyncFn } = require('synckit');
|
||||||
|
const syncQuery = createSyncFn(require.resolve('./pg-worker.js'));
|
||||||
|
|
||||||
|
function convertSqlToPg(sql) {
|
||||||
|
if (!sql || typeof sql !== 'string') return sql;
|
||||||
|
let idx = 0;
|
||||||
|
let s = sql.replace(/\?/g, () => `$${++idx}`);
|
||||||
|
|
||||||
|
if (/^\s*PRAGMA/i.test(s)) return null;
|
||||||
|
|
||||||
|
s = s.replace(/INTEGER\s+PRIMARY\s+KEY\s+AUTOINCREMENT/gi, 'SERIAL PRIMARY KEY');
|
||||||
|
s = s.replace(/INSERT\s+OR\s+IGNORE\s+INTO/gi, 'INSERT INTO');
|
||||||
|
if (/INSERT\s+INTO/i.test(s) && !/ON\s+CONFLICT/i.test(s) && /OR\s+IGNORE/i.test(sql)) {
|
||||||
|
s += ' ON CONFLICT DO NOTHING';
|
||||||
|
}
|
||||||
|
|
||||||
|
s = s.replace(/datetime\s*\(\s*['"]now['"][^)]*\)/gi, 'CURRENT_TIMESTAMP');
|
||||||
|
s = s.replace(/strftime\s*\(\s*['"]%s['"]\s*,\s*['"]now['"]\s*\)/gi, 'EXTRACT(EPOCH FROM CURRENT_TIMESTAMP)');
|
||||||
|
s = s.replace(/strftime\s*\(\s*['"]%s['"]\s*,\s*([^)]+)\s*\)/gi, 'EXTRACT(EPOCH FROM $1)');
|
||||||
|
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeParams(args) {
|
||||||
|
let params = args;
|
||||||
|
if (args.length === 1 && Array.isArray(args[0])) {
|
||||||
|
params = args[0];
|
||||||
|
}
|
||||||
|
return params.map(p => (p === undefined ? null : p));
|
||||||
|
}
|
||||||
|
|
||||||
|
db = {
|
||||||
|
isPg: true,
|
||||||
|
prepare(sql) {
|
||||||
|
const isInsert = /^\s*INSERT\s+INTO/i.test(sql);
|
||||||
|
const hasReturning = /RETURNING/i.test(sql);
|
||||||
|
let runSql = convertSqlToPg(sql);
|
||||||
|
if (isInsert && !hasReturning) {
|
||||||
|
runSql += ' RETURNING id';
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
all(...args) {
|
||||||
|
const pgSql = convertSqlToPg(sql);
|
||||||
|
if (!pgSql) return [];
|
||||||
|
const res = syncQuery({ sql: pgSql, params: normalizeParams(args) });
|
||||||
|
return res.rows;
|
||||||
|
},
|
||||||
|
get(...args) {
|
||||||
|
const pgSql = convertSqlToPg(sql);
|
||||||
|
if (!pgSql) return null;
|
||||||
|
const res = syncQuery({ sql: pgSql, params: normalizeParams(args) });
|
||||||
|
return res.rows[0] || null;
|
||||||
|
},
|
||||||
|
run(...args) {
|
||||||
|
if (!runSql) return { changes: 0, lastInsertRowid: 0 };
|
||||||
|
try {
|
||||||
|
const res = syncQuery({ sql: runSql, params: normalizeParams(args) });
|
||||||
|
const id = (res.rows && res.rows[0] && res.rows[0].id) ? Number(res.rows[0].id) : 0;
|
||||||
|
return { changes: res.rowCount, lastInsertRowid: id };
|
||||||
|
} catch (err) {
|
||||||
|
const plainSql = convertSqlToPg(sql);
|
||||||
|
const res = syncQuery({ sql: plainSql, params: normalizeParams(args) });
|
||||||
|
return { changes: res.rowCount, lastInsertRowid: 0 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
},
|
||||||
|
exec(sql) {
|
||||||
|
const pgSql = convertSqlToPg(sql);
|
||||||
|
if (pgSql) syncQuery({ sql: pgSql, params: [] });
|
||||||
|
},
|
||||||
|
pragma() {},
|
||||||
|
transaction(fn) {
|
||||||
|
return (...args) => fn(...args);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
console.log('🐘 Conectado a PostgreSQL central (recreopay_db)');
|
||||||
|
} else {
|
||||||
|
const Database = require('better-sqlite3');
|
||||||
|
const dbPath = path.join(__dirname, 'recreopay.db');
|
||||||
|
db = new Database(dbPath);
|
||||||
|
db.pragma('journal_mode = WAL');
|
||||||
|
db.pragma('foreign_keys = ON');
|
||||||
|
}
|
||||||
|
|
||||||
function initDatabase() {
|
function initDatabase() {
|
||||||
|
if (isPg) {
|
||||||
|
seedUsuarios();
|
||||||
|
seedDisenosTarjetas();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const schema = `
|
const schema = `
|
||||||
-- 1. Usuarios del Sistema
|
-- 1. Usuarios del Sistema
|
||||||
CREATE TABLE IF NOT EXISTS usuarios (
|
CREATE TABLE IF NOT EXISTS usuarios (
|
||||||
@@ -168,7 +261,8 @@ function initDatabase() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function seedUsuarios() {
|
function seedUsuarios() {
|
||||||
const count = db.prepare('SELECT COUNT(*) as count FROM usuarios').get().count;
|
const res = db.prepare('SELECT COUNT(*) as count FROM usuarios').get();
|
||||||
|
const count = res ? Number(res.count) : 0;
|
||||||
if (count === 0) {
|
if (count === 0) {
|
||||||
console.log('👤 Creando usuarios iniciales de demostración en RecreoPay...');
|
console.log('👤 Creando usuarios iniciales de demostración en RecreoPay...');
|
||||||
const insert = db.prepare('INSERT INTO usuarios (username, password_hash, rol, nombre, telefono, email, activo) VALUES (?, ?, ?, ?, ?, ?, ?)');
|
const insert = db.prepare('INSERT INTO usuarios (username, password_hash, rol, nombre, telefono, email, activo) VALUES (?, ?, ?, ?, ?, ?, ?)');
|
||||||
@@ -215,7 +309,8 @@ function seedUsuarios() {
|
|||||||
|
|
||||||
function seedDisenosTarjetas() {
|
function seedDisenosTarjetas() {
|
||||||
try {
|
try {
|
||||||
const count = db.prepare('SELECT COUNT(*) as count FROM disenos_tarjetas').get().count;
|
const res = db.prepare('SELECT COUNT(*) as count FROM disenos_tarjetas').get();
|
||||||
|
const count = res ? Number(res.count) : 0;
|
||||||
if (count > 0) return;
|
if (count > 0) return;
|
||||||
|
|
||||||
console.log('🎨 Inicializando colección de 16 diseños de tarjetas en RecreoPay...');
|
console.log('🎨 Inicializando colección de 16 diseños de tarjetas en RecreoPay...');
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
const { runAsWorker } = require('synckit');
|
||||||
|
const { Pool, types } = require('pg');
|
||||||
|
|
||||||
|
// Mapear tipos numéricos de PostgreSQL a Number en JavaScript
|
||||||
|
types.setTypeParser(20, (val) => val === null ? null : parseInt(val, 10)); // int8 / bigint
|
||||||
|
types.setTypeParser(21, (val) => val === null ? null : parseInt(val, 10)); // int2 / smallint
|
||||||
|
types.setTypeParser(23, (val) => val === null ? null : parseInt(val, 10)); // int4 / integer
|
||||||
|
types.setTypeParser(1700, (val) => val === null ? null : parseFloat(val)); // numeric / decimal
|
||||||
|
types.setTypeParser(700, (val) => val === null ? null : parseFloat(val)); // float4 / real
|
||||||
|
types.setTypeParser(701, (val) => val === null ? null : parseFloat(val)); // float8 / double precision
|
||||||
|
|
||||||
|
const connectionString = process.env.DATABASE_URL || 'postgresql://postgres:[email protected]:5432/recreopay_db';
|
||||||
|
|
||||||
|
const pool = new Pool({
|
||||||
|
connectionString,
|
||||||
|
max: 10,
|
||||||
|
idleTimeoutMillis: 30000,
|
||||||
|
connectionTimeoutMillis: 5000
|
||||||
|
});
|
||||||
|
|
||||||
|
pool.on('error', (err) => {
|
||||||
|
console.error('⚠️ Error en pool PostgreSQL:', err.message);
|
||||||
|
});
|
||||||
|
|
||||||
|
runAsWorker(async ({ sql, params }) => {
|
||||||
|
try {
|
||||||
|
const res = await pool.query(sql, params || []);
|
||||||
|
return {
|
||||||
|
rows: res.rows || [],
|
||||||
|
rowCount: res.rowCount || 0
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
throw new Error(err.message);
|
||||||
|
}
|
||||||
|
});
|
||||||
+9
-2
@@ -1,7 +1,14 @@
|
|||||||
const express = require('express');
|
|
||||||
const cors = require('cors');
|
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
|
|
||||||
|
// Cargar variables de entorno de .env nativamente
|
||||||
|
try {
|
||||||
|
const envPath = path.join(__dirname, '../.env');
|
||||||
|
if (fs.existsSync(envPath)) process.loadEnvFile(envPath);
|
||||||
|
} catch (e) {}
|
||||||
|
|
||||||
|
const express = require('express');
|
||||||
|
const cors = require('cors');
|
||||||
const QRCode = require('qrcode');
|
const QRCode = require('qrcode');
|
||||||
const { db, initDatabase, debitoCompraTransaction, recargaSaldoTransaction, crearOrdenCompleta, transferenciaP2PTransaction, revertirTransaccionSaldoTransaction } = require('./db');
|
const { db, initDatabase, debitoCompraTransaction, recargaSaldoTransaction, crearOrdenCompleta, transferenciaP2PTransaction, revertirTransaccionSaldoTransaction } = require('./db');
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user