+page.js 2.82 KB
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
  };
}