Files
seguidorDeLotes/nuxt4/server/api/debug/seed-database.post.ts
josedario87 ce8bad68d5
All checks were successful
build-and-deploy / build-and-deploy (push) Successful in 2m46s
Agregar sistema de vinculaciones con registros externos de Metabase
- Nuevo schema BD para vinculaciones_externas con constraint único por período
- Cliente Metabase para consultar Ingresos, Carretas, Salidas y Rechazos
- Endpoints API para registros externos (/api/externos/*) y vinculaciones (/api/vinculaciones/*)
- Composable useRegistrosExternos con lógica de vinculación individual y masiva
- Componentes: TablaRegistros, ModalAsignar, ProgressDashboard
- Tab "Externos" en app.vue con sub-tabs y dashboard de progreso
- LotesCard.vue ahora muestra registros vinculados al lote
2025-11-29 15:25:26 -06:00

96 lines
3.2 KiB
TypeScript

/**
* ⚠️ ⚠️ ⚠️ ENDPOINT DE DEBUG - TEMPORAL ⚠️ ⚠️ ⚠️
*
* POST /api/debug/seed-database
*
* CARGA LOS DATOS DE EJEMPLO EN LA BASE DE DATOS
*
* ⚠️ NO ELIMINAR SIN CONSULTAR A DARIO/DRAGANEL/NUCLEO000 ⚠️
*
* Este endpoint fue creado para desarrollo y debugging.
* Antes de eliminarlo, preguntar si todavía es necesario.
*/
import { getClient } from '../../utils/db'
import { readFile } from 'fs/promises'
import { join } from 'path'
export default defineEventHandler(async (event) => {
try {
console.log('🌱 SEED DATABASE - Cargando datos de ejemplo...')
const client = await getClient()
try {
// Leer los archivos SQL
const schemaPath = join(process.cwd(), 'server', 'database', '01_schema.sql')
const seedPath = join(process.cwd(), 'server', 'database', '02_seed.sql')
const vinculacionesPath = join(process.cwd(), 'server', 'database', '03_vinculaciones_externas.sql')
const schemaSQL = await readFile(schemaPath, 'utf-8')
const seedSQL = await readFile(seedPath, 'utf-8')
const vinculacionesSQL = await readFile(vinculacionesPath, 'utf-8')
await client.query('BEGIN')
// Verificar si las tablas existen
const tablesExist = await client.query(`
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'lotes'
) as exists
`)
const needsSchema = !tablesExist.rows[0].exists
if (needsSchema) {
// Si no existen las tablas, ejecutar schema completo
console.log('📋 Las tablas no existen. Creando schema...')
await client.query(schemaSQL)
console.log('📋 Creando schema de vinculaciones externas...')
await client.query(vinculacionesSQL)
} else {
console.log('📋 Las tablas ya existen. Limpiando datos existentes...')
// Si las tablas existen, limpiar datos antes de cargar seed
await client.query('TRUNCATE TABLE vinculaciones_externas CASCADE')
await client.query('TRUNCATE TABLE operacion_lotes CASCADE')
await client.query('TRUNCATE TABLE operaciones CASCADE')
await client.query('TRUNCATE TABLE lotes CASCADE')
// Asegurar que el schema de vinculaciones esté actualizado
console.log('📋 Actualizando schema de vinculaciones externas...')
await client.query(vinculacionesSQL)
}
// Ejecutar seed (inserta datos de ejemplo)
console.log('📋 Cargando datos de ejemplo...')
await client.query(seedSQL)
await client.query('COMMIT')
console.log('✅ Datos de ejemplo cargados exitosamente')
const message = needsSchema
? 'Schema creado y datos de ejemplo cargados exitosamente'
: 'Datos existentes limpiados y datos de ejemplo cargados exitosamente'
return {
success: true,
message,
}
} catch (error) {
await client.query('ROLLBACK')
throw error
} finally {
client.release()
}
} catch (error: any) {
console.error('❌ Error cargando datos de ejemplo:', error)
throw createError({
statusCode: 500,
statusMessage: 'Error cargando datos de ejemplo',
data: { message: error.message },
})
}
})