+page.server.js
2.8 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import { supabase } from '$lib/supabase';
import { error } from '@sveltejs/kit';
export async function load({ params }) {
const { codigo } = params;
const { data, error: dbError } = await supabase
.schema('ppto')
.from('clas_rubros')
.select('*')
.eq('rubro', codigo);
if (dbError || !data || data.length === 0) {
throw error(404, 'Rubro no encontrado');
}
const rubro = data[0];
// Obtener jerarquía (padres e hijos)
let padres = [];
let hijos = [];
// Buscar padre según nivel
if (rubro.nivel === 'sub_cuenta') {
// Padre es cuenta
const { data: padreData } = await supabase
.schema('ppto')
.from('clas_rubros')
.select('*')
.eq('nivel', 'cuenta')
.eq('tipo', rubro.tipo)
.eq('clase', rubro.clase)
.eq('cuenta', rubro.cuenta);
if (padreData?.length) padres.push(padreData[0]);
}
if (rubro.nivel === 'cuenta' || rubro.nivel === 'sub_cuenta') {
// Padre es clase
const { data: padreData } = await supabase
.schema('ppto')
.from('clas_rubros')
.select('*')
.eq('nivel', 'clase')
.eq('tipo', rubro.tipo)
.eq('clase', rubro.clase);
if (padreData?.length) padres.unshift(padreData[0]);
}
if (rubro.nivel !== 'tipo') {
// Padre es tipo
const { data: padreData } = await supabase
.schema('ppto')
.from('clas_rubros')
.select('*')
.eq('nivel', 'tipo')
.eq('tipo', rubro.tipo);
if (padreData?.length) padres.unshift(padreData[0]);
}
// Buscar hijos según nivel
if (rubro.nivel === 'tipo') {
const { data: hijosData } = await supabase
.schema('ppto')
.from('clas_rubros')
.select('*')
.eq('nivel', 'clase')
.eq('tipo', rubro.tipo)
.order('rubro');
hijos = hijosData?.reduce((acc, item) => {
if (!acc.find(h => h.rubro === item.rubro)) acc.push(item);
return acc;
}, []) || [];
} else if (rubro.nivel === 'clase') {
const { data: hijosData } = await supabase
.schema('ppto')
.from('clas_rubros')
.select('*')
.eq('nivel', 'cuenta')
.eq('tipo', rubro.tipo)
.eq('clase', rubro.clase)
.order('rubro');
hijos = hijosData?.reduce((acc, item) => {
if (!acc.find(h => h.rubro === item.rubro)) acc.push(item);
return acc;
}, []) || [];
} else if (rubro.nivel === 'cuenta') {
const { data: hijosData } = await supabase
.schema('ppto')
.from('clas_rubros')
.select('*')
.eq('nivel', 'sub_cuenta')
.eq('tipo', rubro.tipo)
.eq('clase', rubro.clase)
.eq('cuenta', rubro.cuenta)
.order('rubro');
hijos = hijosData?.reduce((acc, item) => {
if (!acc.find(h => h.rubro === item.rubro)) acc.push(item);
return acc;
}, []) || [];
}
return {
rubro,
padres,
hijos
};
}