+page.js 1.42 KB
export const ssr = false;

import { error } from '@sveltejs/kit';

function getDepth(codigo) {
  return String(codigo).split('.').length;
}

export async function load({ params, fetch }) {
  const { codigo } = params;

  const res = await fetch(`/api/acteco-data?codigo=${codigo}&tipo=clasificador`);
  if (!res.ok) throw error(404, 'Sector económico no encontrado');
  const acteco = await res.json();

  let padres = [];
  let hijos = [];

  try {
    const clasRes = await fetch('/api/acteco-clasificador');
    if (clasRes.ok) {
      const clasificador = await clasRes.json();
      const depth = getDepth(codigo);

      // Padres: todos los ancestros
      if (depth > 1) {
        const parts = String(codigo).split('.');
        const parentCodes = [];
        for (let i = 1; i < parts.length; i++) {
          parentCodes.push(parts.slice(0, i).join('.'));
        }
        padres = clasificador.filter(c => parentCodes.includes(c.acteco));
      }

      // Hijos directos: un nivel más de profundidad, mismo prefijo
      const prefix = codigo + '.';
      const childDepth = depth + 1;
      hijos = clasificador.filter(c =>
        c.acteco.startsWith(prefix) && getDepth(c.acteco) === childDepth
      );

      padres.sort((a, b) => a.acteco.localeCompare(b.acteco));
      hijos.sort((a, b) => a.acteco.localeCompare(b.acteco));
    }
  } catch { /* clasificador optional */ }

  return {
    acteco,
    padres,
    hijos
  };
}