+page.js
2.82 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
import { error } from '@sveltejs/kit';
export async function load({ params, fetch }) {
const municipioUbigeo = params.ubigeo;
// Primero obtener el clasificador para mapear municipio_ubigeo → ubigeo con puntos
const clasRes = await fetch('/api/ubigeo-data?codigo=0&tipo=clasificador');
if (!clasRes.ok) throw error(500, 'Error cargando clasificador');
const clasificador = await clasRes.json();
const match = clasificador.find(c => String(c.municipio_ubigeo) === municipioUbigeo);
if (!match) throw error(404, 'Ubicación no encontrada');
const ubigeoCode = match.ubigeo; // formato "2.7.7"
// Cargar detalle del ubigeo + población en paralelo
const [ubigeoRes, pobRes] = await Promise.all([
fetch(`/api/ubigeo-data?codigo=${ubigeoCode}&tipo=detalle`).then(r => r.ok ? r.json() : null),
fetch('/poblacion.csv').then(r => r.text())
]);
if (!ubigeoRes) throw error(404, 'Ubicación no encontrada');
// Población
const poblacionMap = {};
pobRes.split('\n').slice(1).forEach(line => {
const [cod, , gestion, pob] = line.split(',');
if (cod === municipioUbigeo) {
poblacionMap[parseInt(gestion)] = parseInt(pob);
}
});
// gastos_ingresos ��� resumenData
const gastosIngresos = ubigeoRes.gastos_ingresos || [];
const resumenData = gastosIngresos.map(d => ({
tipo: d.tipo,
gestion: d.gestion,
devengado: d.devengado,
ranking: d.ranking,
codigo: municipioUbigeo,
desc: ubigeoRes.desc_ubigeo
}));
// Última gestión
const gestiones = [...new Set(gastosIngresos.map(d => d.gestion))].filter(g => g <= 2025).sort((a, b) => b - a);
const ultimaGestion = gestiones[0] || 2025;
// Distribuciones de la última gestión
const distEndpoints = [
{ api: 'objetos', dim: 'objeto' },
{ api: 'finfuns', dim: 'finfun' },
{ api: 'actecos', dim: 'acteco' }
];
const distResults = await Promise.all(
distEndpoints.map(async ({ api, dim }) => {
try {
const res = await fetch(`/api/ubigeo-data?codigo=${ubigeoCode}&tipo=${api}`);
if (!res.ok) return [];
const data = await res.json();
if (!Array.isArray(data)) return [];
return data
.filter(d => d.gestion === ultimaGestion)
.map(d => ({
tipo: d.tipo || 'gastos',
dimension: dim,
gestion: d.gestion,
padre: d.padre,
desc_padre: d.desc_padre,
hijo: d.hijo,
desc_hijo: d.desc_hijo,
devengado: d.devengado
}));
} catch { return []; }
})
);
return {
nombre: ubigeoRes.desc_ubigeo || `Ubicación ${municipioUbigeo}`,
nombrePadre: ubigeoRes.desc_departamento || null,
codigo: municipioUbigeo,
ubigeoCode,
resumenData,
distribucionesData: distResults.flat(),
gestionInicial: ultimaGestion,
poblacionMap
};
}