+page.server.js
1.74 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
import { error } from '@sveltejs/kit';
import { API_HOST } from '$lib/api.js';
const API_BASE = API_HOST + '/api/acteco';
// Jerarquía acteco: códigos con punto "1" → "1.1" → "1.1.1"
// Todos tienen nivel "actividad" en la API, derivamos la profundidad del código
function getDepth(codigo) {
return String(codigo).split('.').length;
}
function getParentCode(codigo) {
const parts = String(codigo).split('.');
if (parts.length <= 1) return null;
return parts.slice(0, -1).join('.');
}
export async function load({ params }) {
const { codigo } = params;
const res = await fetch(`${API_BASE}/${codigo}`);
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_BASE}/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
};
}