+page.svelte
13 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
549
<script>
import { onMount } from 'svelte';
import * as d3 from 'd3';
// Estado
let streamData = $state([]);
let loading = $state(true);
let container = $state(null);
let width = $state(0);
let height = $state(500);
let tooltip = $state({ show: false, x: 0, y: 0, data: null });
// Drilldown
let currentLevel = $state('tipo'); // tipo -> clase -> cuenta -> subcuenta
let breadcrumb = $state([{ level: 'tipo', codigo: null, descripcion: 'Todos los ingresos' }]);
let currentParent = $state(null);
// Colores para las categorías
const colorScale = d3.scaleOrdinal()
.range([
'#4A8B6E', '#C9A751', '#8B6E9B', '#6B9FD4', '#D4846B',
'#5B8FA8', '#A8845B', '#7B9B6B', '#9B7B8B', '#6B8B9B',
'#B89B6B', '#6B7B9B', '#9B8B6B', '#7B8B7B', '#8B7B6B',
'#6B9B8B', '#9B6B7B', '#7B6B9B', '#8B9B6B', '#6B8B7B'
]);
// Cargar datos
async function loadData() {
loading = true;
try {
const response = await fetch('/stream1.csv');
const text = await response.text();
const parsed = d3.csvParse(text, d => ({
entidad: +d.entidad,
año: +d.año,
nivel: d.nivel,
codigo: +d.codigo,
descripcion: d.descripcion,
codigo_padre: d.codigo_padre ? +d.codigo_padre : null,
desc_padre: d.desc_padre || null,
devengado: +d.devengado
}));
// Filtrar solo entidad 0 (Todo el Estado)
streamData = parsed.filter(d => d.entidad === 0);
console.log('Stream data loaded:', streamData.length, 'rows');
} catch (err) {
console.error('Error loading data:', err);
}
loading = false;
}
// Obtener datos filtrados para el nivel actual
function getFilteredData() {
let filtered = streamData.filter(d => d.nivel === currentLevel);
if (currentParent !== null) {
filtered = filtered.filter(d => d.codigo_padre === currentParent);
}
return filtered;
}
// Preparar datos para el streamgraph
function prepareStreamData() {
const filtered = getFilteredData();
if (!filtered.length) return { years: [], series: [], keys: [] };
// Agrupar por año
const byYear = d3.group(filtered, d => d.año);
const years = Array.from(byYear.keys()).sort((a, b) => a - b);
// Obtener todas las categorías únicas
const categories = [...new Set(filtered.map(d => d.codigo))];
// Crear estructura para stack
const stackData = years.map(year => {
const yearData = byYear.get(year) || [];
const row = { año: year };
categories.forEach(cat => {
const item = yearData.find(d => d.codigo === cat);
row[cat] = item ? item.devengado : 0;
});
return row;
});
// Crear el stack
const stack = d3.stack()
.keys(categories)
.offset(d3.stackOffsetWiggle)
.order(d3.stackOrderInsideOut);
const series = stack(stackData);
// Agregar descripciones a las series
series.forEach(s => {
const item = filtered.find(d => d.codigo === +s.key);
s.descripcion = item ? item.descripcion : s.key;
});
return { years, series, keys: categories, stackData };
}
// Formatear moneda
function formatMoney(value) {
if (value >= 1e9) return `Bs ${(value / 1e9).toFixed(1)}B`;
if (value >= 1e6) return `Bs ${(value / 1e6).toFixed(1)}M`;
if (value >= 1e3) return `Bs ${(value / 1e3).toFixed(0)}K`;
return `Bs ${value.toFixed(0)}`;
}
// Manejar clic para drilldown
function handleClick(codigo, descripcion) {
const levels = ['tipo', 'clase', 'cuenta', 'subcuenta'];
const currentIndex = levels.indexOf(currentLevel);
if (currentIndex < levels.length - 1) {
const nextLevel = levels[currentIndex + 1];
// Verificar si hay datos en el siguiente nivel
const hasChildren = streamData.some(
d => d.nivel === nextLevel && d.codigo_padre === codigo
);
if (hasChildren) {
currentParent = codigo;
currentLevel = nextLevel;
breadcrumb = [...breadcrumb, { level: nextLevel, codigo, descripcion }];
}
}
}
// Navegar con breadcrumb
function navigateTo(index) {
if (index === 0) {
currentLevel = 'tipo';
currentParent = null;
breadcrumb = [{ level: 'tipo', codigo: null, descripcion: 'Todos los ingresos' }];
} else {
const target = breadcrumb[index];
currentLevel = target.level;
currentParent = index > 0 ? breadcrumb[index - 1].codigo : null;
// Si navegamos a un nivel intermedio, necesitamos el padre correcto
if (index > 0) {
currentParent = breadcrumb[index].codigo;
// Buscar el nivel siguiente
const levels = ['tipo', 'clase', 'cuenta', 'subcuenta'];
const nextLevelIndex = levels.indexOf(target.level) + 1;
if (nextLevelIndex < levels.length) {
currentLevel = levels[nextLevelIndex];
}
}
breadcrumb = breadcrumb.slice(0, index + 1);
}
}
// Efecto para observar tamaño
$effect(() => {
if (!container) return;
const observer = new ResizeObserver(entries => {
for (const entry of entries) {
width = entry.contentRect.width;
}
});
observer.observe(container);
return () => observer.disconnect();
});
onMount(() => {
loadData();
});
// Datos preparados reactivos
let prepared = $derived(prepareStreamData());
// Escalas reactivas
let xScale = $derived(
d3.scaleLinear()
.domain(d3.extent(prepared.years))
.range([60, width - 20])
);
let yExtent = $derived(() => {
if (!prepared.series.length) return [0, 0];
const allValues = prepared.series.flatMap(s => s.flatMap(d => [d[0], d[1]]));
return d3.extent(allValues);
});
let yScale = $derived(
d3.scaleLinear()
.domain(yExtent())
.range([height - 40, 40])
);
// Generador de área
let areaGenerator = $derived(
d3.area()
.x(d => xScale(d.data.año))
.y0(d => yScale(d[0]))
.y1(d => yScale(d[1]))
.curve(d3.curveBasis)
);
</script>
<svelte:head>
<title>Streamgraph - Ingresos del Estado</title>
</svelte:head>
<div class="page">
<header>
<h1>Ingresos del Estado Boliviano</h1>
<p class="subtitle">Streamgraph interactivo con drilldown · 2005-2025</p>
</header>
<!-- Breadcrumb -->
<nav class="breadcrumb">
{#each breadcrumb as crumb, i}
{#if i > 0}
<span class="separator">→</span>
{/if}
<button
class="crumb"
class:active={i === breadcrumb.length - 1}
onclick={() => navigateTo(i)}
disabled={i === breadcrumb.length - 1}
>
{crumb.descripcion}
</button>
{/each}
</nav>
<!-- Nivel actual -->
<div class="level-indicator">
Nivel: <strong>{currentLevel}</strong>
{#if currentLevel !== 'subcuenta'}
<span class="hint">· Clic en una banda para ver detalle</span>
{/if}
</div>
<!-- Contenedor del gráfico -->
<div class="chart-container" bind:this={container}>
{#if loading}
<div class="loading">Cargando datos...</div>
{:else if width > 0 && prepared.series.length > 0}
<svg {width} {height}>
<!-- Eje X -->
<g class="axis-x" transform="translate(0, {height - 35})">
{#each prepared.years.filter((_, i) => i % 2 === 0) as year}
<text x={xScale(year)} y="20" text-anchor="middle" class="axis-label">
{year}
</text>
<line
x1={xScale(year)}
y1="-{height - 80}"
x2={xScale(year)}
y2="0"
class="grid-line"
/>
{/each}
</g>
<!-- Streams -->
{#each prepared.series as serie, i}
{@const color = colorScale(serie.key)}
<path
d={areaGenerator(serie)}
fill={color}
fill-opacity="0.85"
stroke={color}
stroke-width="0.5"
class="stream-path"
class:clickable={currentLevel !== 'subcuenta'}
onmouseenter={(e) => {
tooltip = {
show: true,
x: e.clientX,
y: e.clientY,
data: {
codigo: serie.key,
descripcion: serie.descripcion,
color,
total: d3.sum(serie, d => d[1] - d[0])
}
};
}}
onmousemove={(e) => {
tooltip.x = e.clientX;
tooltip.y = e.clientY;
}}
onmouseleave={() => tooltip.show = false}
onclick={() => handleClick(+serie.key, serie.descripcion)}
/>
{/each}
</svg>
<!-- Leyenda -->
<div class="legend">
{#each prepared.series as serie}
{@const color = colorScale(serie.key)}
<button
class="legend-item"
onclick={() => handleClick(+serie.key, serie.descripcion)}
>
<span class="legend-color" style="background: {color}"></span>
<span class="legend-label">{serie.descripcion}</span>
</button>
{/each}
</div>
{:else}
<div class="no-data">No hay datos para este nivel</div>
{/if}
</div>
<!-- Tooltip -->
{#if tooltip.show && tooltip.data}
<div
class="tooltip"
style="left: {tooltip.x + 15}px; top: {tooltip.y - 10}px;"
>
<div class="tooltip-header" style="border-color: {tooltip.data.color}">
<span class="tooltip-code">{tooltip.data.codigo}</span>
<span class="tooltip-desc">{tooltip.data.descripcion}</span>
</div>
<div class="tooltip-value">
Total acumulado: {formatMoney(tooltip.data.total)}
</div>
{#if currentLevel !== 'subcuenta'}
<div class="tooltip-hint">Clic para ver detalle</div>
{/if}
</div>
{/if}
</div>
<style>
.page {
min-height: 100vh;
background: #1a1a1a;
color: #f5f5f5;
padding: 2rem;
font-family: system-ui, -apple-system, sans-serif;
}
header {
text-align: center;
margin-bottom: 2rem;
}
h1 {
font-size: 2rem;
font-weight: 700;
margin: 0;
color: #f5f5f5;
}
.subtitle {
color: #888;
margin-top: 0.5rem;
}
.breadcrumb {
display: flex;
align-items: center;
gap: 0.5rem;
margin-bottom: 1rem;
flex-wrap: wrap;
}
.separator {
color: #555;
}
.crumb {
background: #2a2a2a;
border: 1px solid #333;
color: #aaa;
padding: 0.4rem 0.8rem;
border-radius: 6px;
cursor: pointer;
font-size: 0.85rem;
transition: all 0.2s;
}
.crumb:hover:not(:disabled) {
background: #333;
color: #fff;
}
.crumb.active {
background: #C9A751;
color: #1a1a1a;
font-weight: 600;
cursor: default;
}
.crumb:disabled {
cursor: default;
}
.level-indicator {
color: #666;
font-size: 0.85rem;
margin-bottom: 1rem;
}
.level-indicator strong {
color: #C9A751;
text-transform: uppercase;
}
.hint {
color: #555;
}
.chart-container {
background: #222;
border-radius: 12px;
padding: 1rem;
min-height: 500px;
position: relative;
}
.loading, .no-data {
display: flex;
align-items: center;
justify-content: center;
height: 400px;
color: #666;
}
svg {
display: block;
}
.axis-label {
fill: #666;
font-size: 12px;
}
.grid-line {
stroke: #333;
stroke-width: 0.5;
stroke-dasharray: 2, 4;
}
.stream-path {
transition: fill-opacity 0.2s, transform 0.2s;
}
.stream-path:hover {
fill-opacity: 1;
}
.stream-path.clickable {
cursor: pointer;
}
.stream-path.clickable:hover {
filter: brightness(1.1);
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
margin-top: 1rem;
padding-top: 1rem;
border-top: 1px solid #333;
}
.legend-item {
display: flex;
align-items: center;
gap: 0.4rem;
background: #2a2a2a;
border: 1px solid #333;
padding: 0.3rem 0.6rem;
border-radius: 4px;
cursor: pointer;
transition: all 0.2s;
}
.legend-item:hover {
background: #333;
}
.legend-color {
width: 12px;
height: 12px;
border-radius: 2px;
flex-shrink: 0;
}
.legend-label {
font-size: 0.75rem;
color: #aaa;
max-width: 150px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tooltip {
position: fixed;
background: rgba(30, 30, 30, 0.95);
backdrop-filter: blur(8px);
border: 1px solid #444;
border-radius: 8px;
padding: 0.75rem 1rem;
pointer-events: none;
z-index: 1000;
max-width: 300px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.4);
}
.tooltip-header {
border-left: 3px solid;
padding-left: 0.5rem;
margin-bottom: 0.5rem;
}
.tooltip-code {
font-family: monospace;
font-size: 0.75rem;
color: #888;
display: block;
}
.tooltip-desc {
font-size: 0.9rem;
color: #f5f5f5;
font-weight: 500;
}
.tooltip-value {
font-size: 0.85rem;
color: #C9A751;
font-weight: 600;
}
.tooltip-hint {
font-size: 0.75rem;
color: #666;
margin-top: 0.3rem;
}
</style>