+page.svelte 22.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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
<script>
  import { supabase } from '$lib/supabase';
  import { onMount } from 'svelte';

  let loading = $state(true);
  let searchQuery = $state('');
  let tipos = $state([]);
  let allItems = $state([]);
  let selectedTipo = $state(null);
  let selectedItem = $state(null);
  let highlightedItem = $state(null);

  onMount(async () => {
    const { data, error } = await supabase
      .schema('ppto')
      .from('clas_rubros')
      .select('*')
      .order('rubro');

    if (!error && data) {
      allItems = data;

      // Extraer tipos únicos (nivel más agregado)
      tipos = data
        .filter(item => item.nivel === 'tipo')
        .reduce((acc, item) => {
          if (!acc.find(t => t.rubro === item.rubro)) {
            acc.push(item);
          }
          return acc;
        }, [])
        .sort((a, b) => a.rubro - b.rubro);

      if (tipos.length > 0) {
        selectedTipo = tipos[0];
      }
    }

    loading = false;
  });

  function getItemsForTipo(tipoCode) {
    if (!tipoCode) return { clases: [] };

    const tipoNum = Math.floor(tipoCode / 1000);

    // Obtener todos los items de este tipo
    const itemsDelTipo = allItems.filter(item => item.tipo === tipoNum && item.nivel !== 'tipo');

    // Encontrar clases únicas desde los valores de la columna 'clase'
    const clasesUnicas = [...new Set(itemsDelTipo.map(i => i.clase).filter(c => c != null))].sort((a, b) => a - b);

    const clases = clasesUnicas.map(claseNum => {
      // Buscar si existe una entrada de nivel 'clase' para esta clase
      const claseEntry = allItems.find(item => item.nivel === 'clase' && item.tipo === tipoNum && item.clase === claseNum);

      // Items de esta clase
      const itemsDeClase = itemsDelTipo.filter(item => item.clase === claseNum);

      // Encontrar cuentas únicas
      const cuentasUnicas = [...new Set(itemsDeClase.map(i => i.cuenta).filter(c => c != null))].sort((a, b) => a - b);

      const cuentas = cuentasUnicas.map(cuentaNum => {
        // Buscar si existe una entrada de nivel 'cuenta' para esta cuenta
        const cuentaEntry = allItems.find(item => item.nivel === 'cuenta' && item.tipo === tipoNum && item.clase === claseNum && item.cuenta === cuentaNum);

        // Sub_cuentas de esta cuenta
        const subcuentas = itemsDeClase
          .filter(item => item.nivel === 'sub_cuenta' && item.cuenta === cuentaNum)
          .reduce((acc, item) => {
            if (!acc.find(s => s.rubro === item.rubro)) acc.push(item);
            return acc;
          }, [])
          .sort((a, b) => a.rubro - b.rubro);

        // Si existe entrada de cuenta, usarla; si no, crear una virtual
        const cuentaData = cuentaEntry || {
          rubro: tipoNum * 1000 + claseNum * 100 + cuentaNum * 10,
          nivel: 'cuenta',
          tipo: tipoNum,
          clase: claseNum,
          cuenta: cuentaNum,
          desc_cuenta: subcuentas[0]?.desc_cuenta || `Cuenta ${cuentaNum}`,
          desc_tipo: subcuentas[0]?.desc_tipo,
          desc_clase: subcuentas[0]?.desc_clase,
          n_variaciones: null,
          descripciones: null
        };

        return { ...cuentaData, subcuentas };
      });

      // Si existe entrada de clase, usarla; si no, crear una virtual
      const claseData = claseEntry || {
        rubro: tipoNum * 1000 + claseNum * 100,
        nivel: 'clase',
        tipo: tipoNum,
        clase: claseNum,
        desc_clase: itemsDeClase[0]?.desc_clase || `Clase ${claseNum}`,
        desc_tipo: itemsDeClase[0]?.desc_tipo,
        n_variaciones: null,
        descripciones: null
      };

      return { ...claseData, cuentas };
    });

    return { clases };
  }

  // Búsqueda global
  function searchGlobal(query) {
    if (!query || query.length < 2) return [];
    const q = query.toLowerCase();

    return allItems
      .filter(item =>
        item.rubro?.toString().includes(q) ||
        item.desc_rubros?.toLowerCase().includes(q) ||
        item.descripciones?.toLowerCase().includes(q)
      )
      .reduce((acc, item) => {
        if (!acc.find(i => i.rubro === item.rubro)) {
          acc.push(item);
        }
        return acc;
      }, [])
      .slice(0, 20);
  }

  function parseDescripciones(descripcionesStr) {
    if (!descripcionesStr) return [];
    try {
      const parsed = JSON.parse(descripcionesStr);
      return parsed.sort((a, b) => {
        const maxYearA = getMaxYear(a.rangos);
        const maxYearB = getMaxYear(b.rangos);
        return maxYearB - maxYearA;
      });
    } catch {
      return [];
    }
  }

  function getMaxYear(rangos) {
    if (!rangos) return 0;
    const years = rangos.match(/\d{4}/g);
    if (!years) return 0;
    return Math.max(...years.map(y => parseInt(y)));
  }

  function selectTipo(tipo) {
    selectedTipo = tipo;
    selectedItem = null;
    searchQuery = '';
    highlightedItem = null;
  }

  function openDetail(item) {
    selectedItem = item;
  }

  function closeDetail() {
    selectedItem = null;
  }

  function goToSearchResult(item) {
    const tipoNum = item.tipo;
    const targetTipo = tipos.find(t => Math.floor(t.rubro / 1000) === tipoNum);

    if (targetTipo) {
      selectedTipo = targetTipo;
      highlightedItem = item.rubro;
      searchQuery = '';

      setTimeout(() => {
        const prefix = item.nivel === 'clase' ? 'cl' : item.nivel === 'cuenta' ? 'cu' : 'sc';
        const element = document.getElementById(`${prefix}-${item.rubro}`);
        if (element) {
          element.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
      }, 100);
    }
  }

  function getNivelLabel(nivel) {
    const labels = { tipo: 'Tipo', clase: 'Clase', cuenta: 'Cuenta', sub_cuenta: 'Subcuenta' };
    return labels[nivel] || nivel;
  }

  // Obtener la descripción correcta según el nivel
  function getDescripcion(item) {
    if (item.nivel === 'tipo') return item.desc_tipo;
    if (item.nivel === 'clase') return item.desc_clase;
    if (item.nivel === 'cuenta') return item.desc_cuenta;
    if (item.nivel === 'sub_cuenta') return item.desc_sub_cuenta;
    return item.desc_rubros;
  }

  let tipoContent = $derived(selectedTipo ? getItemsForTipo(selectedTipo.rubro) : { clases: [] });
  let searchResults = $derived(searchGlobal(searchQuery));
  let isSearching = $derived(searchQuery.length >= 2);
</script>

<svelte:head>
  <title>Rubros | Presupuesto Público</title>
</svelte:head>

<div class="min-h-screen bg-white">
  <!-- Header -->
  <header class="border-b bg-slate-50">
    <div class="max-w-screen-2xl mx-auto px-6 py-4">
      <nav class="text-sm text-slate-500 mb-2">
        <a href="/" class="hover:text-slate-700">Inicio</a>
        <span class="mx-2">/</span>
        <a href="/clasificadores" class="hover:text-slate-700">Clasificadores</a>
        <span class="mx-2">/</span>
        <span class="text-slate-900">Rubros</span>
      </nav>
      <div class="flex items-center justify-between">
        <h1 class="text-2xl font-light text-slate-900">Clasificador por Rubros de Ingresos</h1>
      </div>
    </div>
  </header>

  {#if loading}
    <div class="flex items-center justify-center py-20">
      <p class="text-slate-500">Cargando clasificador...</p>
    </div>
  {:else}
    <div class="max-w-screen-2xl mx-auto flex">
      <!-- Sidebar izquierda: Tipos -->
      <aside class="w-64 flex-shrink-0 border-r bg-slate-50/50">
        <div class="sticky top-0 h-screen overflow-y-auto p-4">
          <!-- Buscador -->
          <div class="mb-6">
            <input
              type="text"
              bind:value={searchQuery}
              placeholder="Buscar..."
              class="w-full px-3 py-2 text-sm border border-slate-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>

          <!-- Resultados de búsqueda -->
          {#if isSearching}
            <div class="mb-4">
              <p class="text-xs text-slate-500 uppercase tracking-wide mb-2">
                {searchResults.length} resultados
              </p>
              <div class="space-y-1">
                {#each searchResults as result}
                  <button
                    class="w-full text-left px-2 py-2 text-sm rounded hover:bg-white hover:shadow-sm transition-all"
                    onclick={() => goToSearchResult(result)}
                  >
                    <span class="text-xs text-slate-400 block">{getNivelLabel(result.nivel)}</span>
                    <span class="font-mono text-xs text-blue-600">{result.rubro}</span>
                    <span class="text-slate-700 ml-1">{getDescripcion(result)}</span>
                  </button>
                {/each}
                {#if searchResults.length === 0}
                  <p class="text-sm text-slate-400 px-2">Sin resultados</p>
                {/if}
              </div>
            </div>
          {:else}
            <!-- Lista de tipos -->
            <nav>
              <p class="text-xs text-slate-500 uppercase tracking-wide mb-3 px-2">Tipos</p>
              <ul class="space-y-1">
                {#each tipos as tipo}
                  <li>
                    <button
                      class="w-full text-left px-3 py-2 rounded-md text-sm transition-all
                        {selectedTipo?.rubro === tipo.rubro
                          ? 'bg-blue-50 text-blue-900 font-medium border-l-2 border-blue-500'
                          : 'text-slate-600 hover:bg-white hover:text-slate-900'}"
                      onclick={() => selectTipo(tipo)}
                    >
                      <span class="font-mono text-xs text-slate-400 block">{tipo.rubro}</span>
                      {getDescripcion(tipo)}
                    </button>
                  </li>
                {/each}
              </ul>
            </nav>
          {/if}
        </div>
      </aside>

      <!-- Contenido principal -->
      <main class="flex-1 min-w-0">
        <div class="px-8 py-6">
          {#if selectedTipo}
            <!-- Título del tipo -->
            <div class="mb-8 pb-6 border-b">
              <p class="text-sm font-mono text-slate-400 mb-1">{selectedTipo.rubro}</p>
              <h2 class="text-xl font-medium text-slate-900 mb-2 flex items-center gap-3">
                {getDescripcion(selectedTipo)}
                <a
                  href="/rubro/{selectedTipo.rubro}"
                  class="text-slate-300 hover:text-blue-500 transition-colors"
                  title="Ver detalle"
                >
                  <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                  </svg>
                </a>
              </h2>
              {#if selectedTipo.descripciones}
                {@const tipoDescs = parseDescripciones(selectedTipo.descripciones)}
                {#if tipoDescs.length > 0}
                  <p class="text-slate-600 leading-relaxed">{tipoDescs[0].descripcion}</p>
                  {#if selectedTipo.n_variaciones > 1}
                    <button
                      class="text-sm text-orange-500 hover:text-orange-700 mt-2 transition-colors underline decoration-dotted decoration-orange-300 hover:decoration-orange-500 cursor-pointer"
                      onclick={() => openDetail(selectedTipo)}
                    >
                      Ver {selectedTipo.n_variaciones} variaciones históricas
                    </button>
                  {/if}
                {/if}
              {/if}
            </div>

            <!-- Clases -->
            <div class="space-y-8">
              {#each tipoContent.clases as clase}
                {@const claseDescs = parseDescripciones(clase.descripciones)}
                <section
                  id="cl-{clase.rubro}"
                  class="scroll-mt-4 {highlightedItem === clase.rubro ? 'ring-2 ring-blue-200 rounded-lg' : ''}"
                >
                  <div class="flex items-start gap-4 mb-3">
                    <span class="font-mono text-sm text-slate-400 pt-1">{clase.rubro}</span>
                    <div class="flex-1">
                      <h3 class="text-lg font-medium text-slate-900 flex items-center gap-2">
                        <span class="text-left">{getDescripcion(clase)}</span>
                        {#if clase.n_variaciones > 1}
                          <button
                            class="text-xs font-normal text-orange-500 hover:text-orange-700 transition-colors underline decoration-dotted decoration-orange-300 hover:decoration-orange-500 cursor-pointer"
                            onclick={() => openDetail(clase)}
                            title="Ver variaciones de descripción"
                          >
                            {clase.n_variaciones} var.
                          </button>
                        {/if}
                        <a
                          href="/rubro/{clase.rubro}"
                          class="text-slate-300 hover:text-blue-500 transition-colors"
                          title="Ver página de detalle"
                        >
                          <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                          </svg>
                        </a>
                      </h3>
                      {#if claseDescs.length > 0}
                        <p class="text-sm text-slate-600 mt-1 leading-relaxed">{claseDescs[0].descripcion}</p>
                      {/if}
                    </div>
                  </div>

                  <!-- Cuentas -->
                  {#if clase.cuentas?.length > 0}
                    <div class="ml-16 space-y-4 border-l-2 border-slate-100 pl-6">
                      {#each clase.cuentas as cuenta}
                        {@const cuentaDescs = parseDescripciones(cuenta.descripciones)}
                        <div
                          id="cu-{cuenta.rubro}"
                          class="scroll-mt-4 {highlightedItem === cuenta.rubro ? 'ring-2 ring-blue-200 rounded-lg p-2 -ml-2' : ''}"
                        >
                          <div class="flex items-start gap-3">
                            <span class="font-mono text-xs text-slate-400 pt-0.5">{cuenta.rubro}</span>
                            <div class="flex-1">
                              <h4 class="text-sm font-medium text-slate-800 flex items-center gap-2">
                                <span class="text-left">{getDescripcion(cuenta)}</span>
                                {#if cuenta.n_variaciones > 1}
                                  <button
                                    class="text-xs font-normal text-orange-500 hover:text-orange-700 transition-colors underline decoration-dotted decoration-orange-300 hover:decoration-orange-500 cursor-pointer"
                                    onclick={() => openDetail(cuenta)}
                                    title="Ver variaciones de descripción"
                                  >
                                    {cuenta.n_variaciones} var.
                                  </button>
                                {/if}
                                <a
                                  href="/rubro/{cuenta.rubro}"
                                  class="text-slate-300 hover:text-blue-500 transition-colors"
                                  title="Ver página de detalle"
                                >
                                  <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                                  </svg>
                                </a>
                              </h4>
                              {#if cuentaDescs.length > 0}
                                <p class="text-xs text-slate-500 mt-1 leading-relaxed">{cuentaDescs[0].descripcion}</p>
                              {/if}
                            </div>
                          </div>

                          <!-- Subcuentas -->
                          {#if cuenta.subcuentas?.length > 0}
                            <div class="ml-12 mt-3 space-y-2 border-l border-slate-100 pl-4">
                              {#each cuenta.subcuentas as subcuenta}
                                {@const subcuentaDescs = parseDescripciones(subcuenta.descripciones)}
                                <div
                                  id="sc-{subcuenta.rubro}"
                                  class="scroll-mt-4 {highlightedItem === subcuenta.rubro ? 'ring-2 ring-blue-200 rounded p-1 -ml-1' : ''}"
                                >
                                  <div class="flex items-start gap-2">
                                    <span class="font-mono text-xs text-slate-300">{subcuenta.rubro}</span>
                                    <div class="flex-1">
                                      <span class="flex items-center gap-2">
                                        <span class="text-xs text-slate-700">{getDescripcion(subcuenta)}</span>
                                        {#if subcuenta.n_variaciones > 1}
                                          <button
                                            class="text-xs text-orange-500 hover:text-orange-700 transition-colors underline decoration-dotted decoration-orange-300 hover:decoration-orange-500 cursor-pointer"
                                            onclick={() => openDetail(subcuenta)}
                                            title="Ver variaciones de descripción"
                                          >
                                            {subcuenta.n_variaciones} var.
                                          </button>
                                        {/if}
                                        <a
                                          href="/rubro/{subcuenta.rubro}"
                                          class="text-slate-300 hover:text-blue-500 transition-colors"
                                          title="Ver página de detalle"
                                        >
                                          <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                                          </svg>
                                        </a>
                                      </span>
                                      {#if subcuentaDescs.length > 0}
                                        <p class="text-xs text-slate-400 mt-0.5">{subcuentaDescs[0].descripcion}</p>
                                      {/if}
                                    </div>
                                  </div>
                                </div>
                              {/each}
                            </div>
                          {/if}
                        </div>
                      {/each}
                    </div>
                  {/if}
                </section>
              {/each}
            </div>
          {/if}
        </div>
      </main>

      <!-- Sidebar derecha: En esta página -->
      <aside class="w-56 flex-shrink-0 hidden xl:block">
        <div class="sticky top-0 h-screen overflow-y-auto p-4 border-l">
          <p class="text-xs text-slate-500 uppercase tracking-wide mb-3">En esta página</p>
          {#if selectedTipo && !isSearching}
            <nav class="space-y-2">
              {#each tipoContent.clases as clase}
                <div>
                  <a
                    href="#cl-{clase.rubro}"
                    class="block text-sm text-slate-600 hover:text-blue-600 truncate"
                    title="{getDescripcion(clase)}"
                  >
                    {getDescripcion(clase)}
                  </a>
                  {#if clase.cuentas?.length > 0}
                    <div class="ml-3 mt-1 space-y-1 border-l border-slate-100 pl-2">
                      {#each clase.cuentas.slice(0, 5) as cuenta}
                        <a
                          href="#cu-{cuenta.rubro}"
                          class="block text-xs text-slate-400 hover:text-blue-600 truncate"
                          title="{getDescripcion(cuenta)}"
                        >
                          {getDescripcion(cuenta)}
                        </a>
                      {/each}
                      {#if clase.cuentas.length > 5}
                        <span class="text-xs text-slate-300">+{clase.cuentas.length - 5} más</span>
                      {/if}
                    </div>
                  {/if}
                </div>
              {/each}
            </nav>
          {/if}
        </div>
      </aside>
    </div>
  {/if}
</div>

<!-- Modal de detalle -->
{#if selectedItem}
  <div class="fixed inset-0 bg-black/40 flex items-center justify-center p-4 z-50" onclick={closeDetail}>
    <div
      class="bg-white rounded-xl shadow-2xl max-w-2xl w-full max-h-[85vh] overflow-hidden flex flex-col"
      onclick={(e) => e.stopPropagation()}
    >
      <div class="px-6 py-4 border-b bg-slate-50 flex justify-between items-start">
        <div>
          <p class="text-xs text-slate-500 uppercase tracking-wide">{getNivelLabel(selectedItem.nivel)}</p>
          <h3 class="text-lg font-medium text-slate-900 mt-1">
            <span class="font-mono text-slate-400">{selectedItem.rubro}</span>
            <span class="mx-2">·</span>
            {getDescripcion(selectedItem)}
          </h3>
        </div>
        <button
          onclick={closeDetail}
          class="text-slate-400 hover:text-slate-600 text-2xl leading-none"
        >
          &times;
        </button>
      </div>

      <div class="p-6 overflow-y-auto flex-1">
        <h4 class="text-sm font-medium text-slate-700 mb-4">
          {#if selectedItem.n_variaciones > 1}
            Descripciones ({selectedItem.n_variaciones} variaciones)
          {:else}
            Descripción
          {/if}
        </h4>

        <div class="space-y-4">
          {#each parseDescripciones(selectedItem.descripciones) as desc, i}
            <div class="border-l-2 {i === 0 ? 'border-blue-500 bg-blue-50/50' : 'border-slate-200'} pl-4 py-2 rounded-r">
              <p class="text-xs text-slate-500 mb-2">
                {#if i === 0 && selectedItem.n_variaciones > 1}
                  <span class="text-blue-600 font-medium">Vigente</span>
                  <span class="mx-1">·</span>
                {/if}
                {desc.rangos}
              </p>
              <p class="text-sm text-slate-700 leading-relaxed">{desc.descripcion}</p>
            </div>
          {/each}
        </div>
      </div>
    </div>
  </div>
{/if}