+page.server.js 3.7 KB
import { supabase } from '$lib/supabase';
import { error } from '@sveltejs/kit';

// Funciones para derivar jerarquía del código rubro
// Jerarquía: Tipo (XX000) → Clase (XXX00) → Cuenta (XXXX0) → Subcuenta (XXXXX)

function getTipoCode(rubro) {
  // Primeros 2 dígitos + 000 → ej: 11000, 12000
  return rubro.substring(0, 2) + '000';
}

function getClaseCode(rubro) {
  // Primeros 3 dígitos + 00 → ej: 11100, 11200
  return rubro.substring(0, 3) + '00';
}

function getCuentaCode(rubro) {
  // Primeros 4 dígitos + 0 → ej: 11110, 11120
  return rubro.substring(0, 4) + '0';
}

function getNivelFromCode(rubro) {
  // Determinar nivel basado en el patrón de ceros
  if (rubro.endsWith('000')) return 'tipo';      // XX000
  if (rubro.endsWith('00')) return 'clase';      // XXX00
  if (rubro.endsWith('0')) return 'cuenta';      // XXXX0
  return 'sub_cuenta';                            // XXXXX
}

function getNextNivel(nivel) {
  const niveles = { tipo: 'clase', clase: 'cuenta', cuenta: 'sub_cuenta' };
  return niveles[nivel] || null;
}

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];
  const nivel = rubro.nivel || getNivelFromCode(codigo);

  // Obtener jerarquía (padres e hijos)
  let padres = [];
  let hijos = [];

  // Buscar padres según nivel
  if (nivel === 'sub_cuenta') {
    // Padres: tipo, clase, cuenta
    const tipoCode = getTipoCode(codigo);
    const claseCode = getClaseCode(codigo);
    const cuentaCode = getCuentaCode(codigo);

    const { data: padresData } = await supabase
      .schema('ppto')
      .from('clas_rubros')
      .select('*')
      .in('rubro', [tipoCode, claseCode, cuentaCode])
      .order('rubro');

    if (padresData) padres = padresData;
  } else if (nivel === 'cuenta') {
    // Padres: tipo, clase
    const tipoCode = getTipoCode(codigo);
    const claseCode = getClaseCode(codigo);

    const { data: padresData } = await supabase
      .schema('ppto')
      .from('clas_rubros')
      .select('*')
      .in('rubro', [tipoCode, claseCode])
      .order('rubro');

    if (padresData) padres = padresData;
  } else if (nivel === 'clase') {
    // Padre: tipo
    const tipoCode = getTipoCode(codigo);

    const { data: padresData } = await supabase
      .schema('ppto')
      .from('clas_rubros')
      .select('*')
      .eq('rubro', tipoCode);

    if (padresData) padres = padresData;
  }
  // tipo no tiene padres

  // Buscar hijos según nivel
  const nextNivel = getNextNivel(nivel);
  if (nextNivel) {
    const { data: hijosData } = await supabase
      .schema('ppto')
      .from('clas_rubros')
      .select('*')
      .eq('nivel', nextNivel)
      .like('rubro', `${codigo.replace(/0+$/, '')}%`)
      .order('rubro');

    if (hijosData) {
      // Filtrar solo hijos directos (siguiente nivel)
      hijos = hijosData.filter(h => {
        if (nivel === 'tipo') {
          // Hijos de tipo son clase: XXX00 donde XX = tipo
          return h.rubro.startsWith(codigo.substring(0, 2)) && h.nivel === 'clase';
        } else if (nivel === 'clase') {
          // Hijos de clase son cuenta: XXXX0 donde XXX = clase
          return h.rubro.startsWith(codigo.substring(0, 3)) && h.nivel === 'cuenta';
        } else if (nivel === 'cuenta') {
          // Hijos de cuenta son sub_cuenta: XXXXX donde XXXX = cuenta
          return h.rubro.startsWith(codigo.substring(0, 4)) && h.nivel === 'sub_cuenta';
        }
        return false;
      });
    }
  }

  return {
    rubro,
    padres,
    hijos
  };
}