File size: 43,373 Bytes
6f10462 | 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 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 | <!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>East Java Legal Cases Mapping</title>
<!-- Custom CSS -->
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<!-- Font Awesome untuk icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<!-- Chart.js untuk diagram interaktif -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
</head>
<body>
<!-- Header -->
<header class="header">
<div class="container">
<h1 class="logo">
<i class="fas fa-balance-scale"></i>
East Java Legal Cases Mapping
</h1>
<nav class="nav">
<ul>
<li><a href="#home" class="nav-link">Home</a></li>
<li><a href="#statistics" class="nav-link">Statistics</a></li>
<li><a href="#about" class="nav-link">About</a></li>
</ul>
</nav>
</div>
</header>
<!-- Main Content -->
<main>
<!-- Search and Map Section -->
<section id="home" class="map-section">
<div class="container-fluid" style="max-width: 100%; padding: 20px 40px;">
<!-- Summary Widgets -->
<!-- Pastikan Font Awesome sudah di-include -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
<div class="summary-container" style="
display: flex;
gap: 20px;
margin-bottom: 30px;
flex-wrap: wrap;
">
<!-- Total Putusan -->
<div class="summary-card" style="
flex: 1 1 200px;
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
text-align: center;
">
<div class="summary-icon" style="font-size: 24px; color: #2E86AB; margin-bottom: 8px;">
<i class="fas fa-gavel"></i>
</div>
<div class="summary-title" style="font-size: 14px; color: #555;">Total Criminal Verdicts</div>
<div class="summary-value" id="totalPutusan" style="font-size: 24px; font-weight: bold;">0</div>
</div>
<!-- Total Pengadilan Negeri -->
<div class="summary-card" style="
flex: 1 1 200px;
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
text-align: center;
">
<div class="summary-icon" style="font-size: 24px; color: #FF7F0E; margin-bottom: 8px;">
<i class="fas fa-landmark"></i>
</div>
<div class="summary-title" style="font-size: 14px; color: #555;">Total District Courts</div>
<div class="summary-value" id="totalPN" style="font-size: 24px; font-weight: bold;">0</div>
</div>
</div>
<!-- Filter Controls -->
<div class="filter-panel" style="background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
margin-bottom: 20px;
display: flex;
gap: 15px;
align-items: flex-end;
flex-wrap: wrap;">
<div style="flex: 1; min-width: 200px;">
<label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Categories:</label>
<select id="categoryFilter" style="width: 100%;
padding: 10px 15px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 14px;">
<option value="all">All Categories</option>
<option value="pidana">Pidana Umum</option>
</select>
</div>
<div style="flex: 1; min-width: 200px;">
<label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Years:</label>
<select id="yearFilter" style="width: 100%;
padding: 10px 15px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 14px;">
<option value="all">All Years</option>
<!-- Will be populated dynamically from API -->
</select>
</div>
<div style="flex: 1; min-width: 200px;">
<label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Crime Types:</label>
<select id="crimeFilter" style="width: 100%;
padding: 10px 15px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 14px;">
<option value="all">All Types</option>
<!-- Will be populated dynamically from API -->
</select>
</div>
<div style="flex: 1; min-width: 200px;">
<label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Cities/Regencies:</label>
<select id="cityFilter" style="width: 100%;
padding: 10px 15px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 14px;">
<option value="all">All Regencies</option>
<!-- Will be populated dynamically from API -->
</select>
</div>
</div>
<!-- Interactive Heatmap with Click-to-Zoom -->
<div style="background: white;
border-radius: 10px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
<div style="background: linear-gradient(135deg, #2C5F8D 0%, #1e3c72 100%);
padding: 15px;
color: white;">
<h3 style="margin: 0; font-size: 18px;">
East Java Legal Cases Interactive Map
</h3>
<p style="margin: 5px 0 0 0; font-size: 13px; opacity: 0.9;">
Hover for more information • Click regency for detailed cases
</p>
</div>
<iframe id="mapIframe" src="{{ url_for('map_view') }}"
style="width: 100%;
height: 650px;
border: none;">
</iframe>
</div>
<!-- Charts Section - Diagram Interaktif dan Dinamis -->
<div class="charts-row" style="
margin-top: 60px;
display: flex;
gap: 20px;
flex-wrap: wrap;
">
<!-- Chart 1 -->
<div style="
flex: 1;
min-width: 400px;
max-width: 50%;
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
">
<h3 id="yearHeading" style="margin:0 0 15px 0; font-size:18px;">
Case Trends Per Year
</h3>
<canvas id="casesYearChart" height="120"></canvas>
</div>
<!-- Chart 2 -->
<div style="
flex: 1;
min-width: 400px;
max-width: 50%;
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
">
<h3 id="seasonalityHeading" style="margin:0 0 15px 0; font-size:18px;">
Case Pattern Per Month
</h3>
<canvas id="seasonalityChart"></canvas>
</div>
<!-- Chart 3 -->
<div style="
width: 100%;
margin-top: 30px;
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
">
<h3 id="forecast" style="margin:0 0 15px 0; font-size:18px;">
Case Forecast for Next Year
</h3>
<canvas id="forecastChart" height="120"></canvas>
</div>
<!-- Chart 4: Frekuensi 10 Jenis Tindak Pidana -->
<div style="
width: 100%;
margin-top: 30px;
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
">
<h3 style="margin:0 0 15px 0; font-size:18px;">
10 Highest Types of Crimes
</h3>
<canvas id="crimeTypeChart"></canvas>
</div>
<div style="
width: 100%;
margin-top: 20px;
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
">
<h3 id="stackedHeading" style="margin-bottom: 15px; font-size: 18px;">
Sentencing Patterns for the 10 Highest Crimes
</h3>
<canvas id="stackedPNChart"></canvas>
</div>
<table id="kasusTable" class="table table-striped">
<thead>
<tr id="kasusHead"></tr>
</thead>
<tbody id="kasusBody"></tbody>
</table>
<div class="pagination-container" style="
display: flex;
gap: 10px;
align-items: center;
justify-content: flex-start;
margin-top: 15px;
flex-wrap: wrap;
">
<button id="prevKasus" class="btn-pagination">Prev</button>
<span id="kasusPageInfo" style="font-weight: 500; min-width: 80px; text-align: center;"></span>
<button id="nextKasus" class="btn-pagination">Next</button>
</div>
<style>
.btn-pagination {
background-color: #2E86AB;
color: white;
border: none;
padding: 6px 14px;
border-radius: 6px;
font-size: 0.9rem;
cursor: pointer;
transition: all 0.2s ease;
box-shadow: 0 2px 4px rgba(0,0,0,0.15);
}
.btn-pagination:hover {
background-color: #1B4F72;
transform: translateY(-1px);
box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}
.btn-pagination:disabled {
background-color: #cccccc;
cursor: not-allowed;
box-shadow: none;
}
</style>
</div>
</div>
</section>
</main>
<!-- Footer -->
<footer class="footer">
<div class="container">
</div>
</footer>
<!-- JavaScript for Filter Functionality -->
<script>
// Filter change events
// ==================== FILTER FUNCTIONALITY ====================
let currentFilters = {
year: 'all',
crime: 'all',
city: 'all'
};
let allCharts = {}; // Store chart instances
let filtersInitialized = false; // Track if event listeners are attached
function animateNumber(element, target) {
let current = 0;
const increment = target / 50;
const timer = setInterval(() => {
current += increment;
if (current >= target) {
element.textContent = target.toLocaleString();
clearInterval(timer);
} else {
element.textContent = Math.floor(current).toLocaleString();
}
}, 20);
}
function applyFilters() {
const year = document.getElementById('yearFilter').value;
const crime = document.getElementById('crimeFilter').value;
const city = document.getElementById('cityFilter').value;
currentFilters.year = year;
currentFilters.crime = crime;
currentFilters.city = city;
// Build query string
const params = new URLSearchParams();
if (year !== 'all') params.append('year', year);
if (crime !== 'all') params.append('crime', crime);
if (city !== 'all') params.append('city', city);
const queryString = params.toString();
const statsUrl = '/api/statistics' + (queryString ? '?' + queryString : '');
const mapUrl = '/map' + (queryString ? '?' + queryString : '');
// Log for debugging
console.log('Applying filters - Year:', year, 'Crime:', crime, 'City:', city);
console.log('Stats URL:', statsUrl);
console.log('Map URL:', mapUrl);
// Reload map with filters
const mapIframe = document.getElementById('mapIframe');
if (mapIframe) {
mapIframe.src = mapUrl;
console.log('Map iframe reloaded');
}
// Reload data with filters
loadStatistics(statsUrl);
}
// ==================== CHART.JS - DIAGRAM INTERAKTIF ====================
function loadStatistics(url) {
fetch(url)
.then(response => response.json())
.then(apiData => {
console.log('Data dari API:', apiData);
// Update statistics section
// updateStatistics(apiData);
if (apiData) {
document.getElementById("totalPutusan").innerText = apiData.total_cases || 0;
document.getElementById("totalPN").innerText = apiData.total_pn || 0;
}
// Populate year filter dropdown if year_options available
if (apiData.year_options) {
const yearFilter = document.getElementById('yearFilter');
const prev = currentFilters.year;
yearFilter.innerHTML = '<option value="all">All Years</option>';
apiData.year_options.forEach(year => {
const option = document.createElement('option');
option.value = year.value;
option.textContent = `${year.label} (${year.count.toLocaleString()})`;
yearFilter.appendChild(option);
});
yearFilter.value = prev;
}
// Populate crime filter dropdown if crime_types available
if (apiData.crime_types) {
const crimeFilter = document.getElementById('crimeFilter');
const prev = currentFilters.crime;
crimeFilter.innerHTML = '<option value="all">All Types</option>';
apiData.crime_types.slice(0, 20).forEach(crime => {
const option = document.createElement('option');
option.value = crime.value;
option.textContent = `${crime.label} (${crime.count.toLocaleString()})`;
crimeFilter.appendChild(option);
});
crimeFilter.value = prev;
}
// Populate city filter dropdown if city_options available
if (apiData.city_options && !document.getElementById('cityFilter').dataset.populated) {
const cityFilter = document.getElementById('cityFilter');
apiData.city_options.forEach(city => {
const option = document.createElement('option');
option.value = city.value;
option.textContent = city.label;
cityFilter.appendChild(option);
});
cityFilter.dataset.populated = 'true';
}
// Initialize event listeners after dropdowns are populated
if (!filtersInitialized) {
document.getElementById('yearFilter').addEventListener('change', applyFilters);
document.getElementById('crimeFilter').addEventListener('change', applyFilters);
document.getElementById('cityFilter').addEventListener('change', applyFilters);
// document.getElementById('resetFilter').addEventListener('click', resetFilters);
filtersInitialized = true;
console.log('Filter event listeners initialized');
}
// Clean existing chart instances
Object.values(allCharts).forEach(ch => ch.destroy());
// === TREN KASUS TAHUNAN - LINE CHART INTERAKTIF ===
if (apiData.year_options) {
const ctx = document.getElementById('casesYearChart').getContext('2d');
// Urutkan ascending khusus untuk chart
const sortedYears = apiData.year_options.slice().reverse();
const years = sortedYears.map(x => Number(x.value));
const counts = sortedYears.map(x => Number(x.count));
const avgCases = counts.reduce((a, b) => a + b, 0) / counts.length;
// Hapus chart lama
if (allCharts.casesYearChart) allCharts.casesYearChart.destroy();
// Hitung perubahan signifikan (>15%)
const annotations = [];
apiData.year_options.forEach((item, i) => {
if (i === 0) return;
const prev = apiData.year_options[i - 1].count;
const change = ((item.count - prev) / prev) * 100;
if (Math.abs(change) > 15) {
annotations.push({
type: 'label',
xValue: Number(item.value),
yValue: Number(item.count),
backgroundColor: 'white',
borderColor: '#444',
borderWidth: 1,
padding: 6,
content: `${change > 0 ? '+' : ''}${change.toFixed(0)}%`,
color: change > 0 ? 'green' : 'red',
font: { weight: 'bold' },
yAdjust: -20
});
}
});
allCharts.casesYearChart = new Chart(ctx, {
type: 'line',
data: {
labels: years,
datasets: [{
label: `Yearly Case Trends (Average ${avgCases.toFixed(0)} Case)`,
data: counts,
borderWidth: 3,
tension: 0.25,
borderColor: '#2E86AB',
pointBackgroundColor: 'white',
pointBorderColor: '#2E86AB',
pointBorderWidth: 2,
pointRadius: 6,
pointHoverRadius: 7
}]
},
options: {
responsive: true,
plugins: {
legend: { display: false },
tooltip: {
callbacks: {
label: function (ctx) {
const index = ctx.dataIndex;
const current = ctx.raw;
if (index === 0) {
return `${current.toLocaleString()} case (first year)`;
}
const prev = ctx.chart.data.datasets[0].data[index - 1];
const change = ((current - prev) / prev) * 100;
const sign = change >= 0 ? '+' : '';
return `${current.toLocaleString()} case (${sign}${change.toFixed(1)}%)`;
}
}
},
annotation: {
annotations: annotations
}
},
scales: {
x: {
ticks: { autoSkip: false }
},
y: {
beginAtZero: false,
grid: { color: 'rgba(0,0,0,0.1)' }
}
}
}
});
document.getElementById('yearHeading').textContent =
allCharts.casesYearChart.data.datasets[0].label;
}
if (apiData.seasonal_data) {
const ctx = document.getElementById('seasonalityChart').getContext('2d');
// Nama bulan
const monthNames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
// Pastikan full 12 bulan tetap ada
const fullData = Array.from({ length: 12 }, (_, i) => {
const entry = apiData.seasonal_data.find(x => Number(x.month) === i + 1);
return entry ? Number(entry.count) : 0;
});
const months = Array.from({ length: 12 }, (_, i) => i + 1);
// Highest & lowest bulan dengan kasus > 0
const filtered = fullData.filter(x => x > 0);
const maxVal = Math.max(...filtered);
const minVal = Math.min(...filtered);
const maxMonth = fullData.indexOf(maxVal) + 1;
const minMonth = fullData.indexOf(minVal) + 1;
// Persentase perubahan bulan-ke-bulan
const percentChanges = fullData.map((count, i) => {
if (i === 0) return null;
const prev = fullData[i - 1];
return prev > 0 ? ((count - prev) / prev) * 100 : null;
});
// Rata-rata kasus per bulan
const avgCases = fullData.reduce((a, b) => a + b, 0) / fullData.length;
// Hapus chart lama
if (allCharts.seasonalityChart) allCharts.seasonalityChart.destroy();
allCharts.seasonalityChart = new Chart(ctx, {
type: 'bar',
data: {
labels: monthNames,
datasets: [{
label: `Monthly Cases (Average ${avgCases.toFixed(0)} Case)`,
data: fullData,
borderWidth: 2,
backgroundColor: fullData.map((v, i) =>
(i + 1 === maxMonth) ? '#E57373' :
(i + 1 === minMonth) ? '#81C784' :
'#B0C4DE'
),
borderColor: fullData.map((v, i) =>
(i + 1 === maxMonth) ? '#B71C1C' :
(i + 1 === minMonth) ? '#1B5E20' :
'#1E3A5F'
)
}]
},
options: {
responsive: true,
plugins: {
legend: { display: false },
tooltip: {
callbacks: {
label: ctx => {
const monthIdx = ctx.dataIndex;
const raw = ctx.raw.toLocaleString();
const pct = percentChanges[monthIdx];
if (pct === null) return ` ${raw} kasus`;
const sign = pct > 0 ? '+' : '';
return ` ${raw} case (${sign}${pct.toFixed(1)}%)`;
}
}
}
},
scales: {
y: {
beginAtZero: true,
grid: { color: 'rgba(0,0,0,0.1)' }
}
}
}
});
document.getElementById('seasonalityHeading').textContent =
allCharts.seasonalityChart.data.datasets[0].label;
}
// === CHART FORECAST: TREND HISTORIS + PREDIKSI ===
if (apiData.forecast_result) {
const history = apiData.forecast_result.history || [];
const future = apiData.forecast_result.forecast || [];
// Jika tidak ada data, hentikan
if (history.length === 0 && future.length === 0) {
console.warn("Forecast data empty");
return;
}
const allLabels = [
...history.map(r => r.date),
...future.map(r => r.date)
];
const historyValues = history.map(r => r.count);
// Forecast dimulai setelah historis → sisipkan null di awal
const forecastValues = [
...Array(history.length).fill(null),
...future.map(r => r.forecast)
];
const ctxForecast = document.getElementById('forecastChart').getContext('2d');
if (allCharts.forecastChart) allCharts.forecastChart.destroy();
allCharts.forecastChart = new Chart(ctxForecast, {
type: 'line',
data: {
labels: allLabels,
datasets: [
{
label: "Historical Data",
data: historyValues,
borderWidth: 2,
tension: 0.3
},
{
label: "Forecast",
data: forecastValues,
borderWidth: 2,
borderDash: [6, 4],
tension: 0.3
}
]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'top'
},
tooltip: {
callbacks: {
label: ctx => {
const val = ctx.raw;
if (val === null) return null;
return `${ctx.dataset.label}: ${val.toLocaleString()}`;
}
}
}
},
scales: {
x: {
ticks: {
autoSkip: true,
maxTicksLimit: 12
}
},
y: {
beginAtZero: true
}
}
}
});
// Untuk debugging
document.getElementById('forecastChart').textContent =
allCharts.forecastChart.data.datasets[0].label;
}
// === CHART 3: FREKUENSI 10 JENIS TINDAK PIDANA TERTINGGI ===
if (apiData.crime_types) {
// Ambil urutan berdasarkan count
const sortedCrimeTypes = apiData.crime_types
.sort((a, b) => b.count - a.count)
.slice(0, 10); // ambil 10 teratas
const labels = sortedCrimeTypes.map(x => x.label);
const values = sortedCrimeTypes.map(x => x.count);
const ctx3 = document.getElementById('crimeTypeChart').getContext('2d');
if (allCharts.crimeTypeChart) allCharts.crimeTypeChart.destroy();
allCharts.crimeTypeChart = new Chart(ctx3, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Total Cases',
data: values,
borderWidth: 1
}]
},
options: {
indexAxis: 'y', // horizontal bar
responsive: true,
plugins: {
legend: { display: false },
tooltip: {
callbacks: {
label: ctx => ctx.raw.toLocaleString()
}
}
},
scales: {
x: {
beginAtZero: true,
ticks: {
callback: value => value.toLocaleString()
}
}
}
}
});
document.getElementById('crimeTypeChart').textContent =
allCharts.crimeTypeChart.data.datasets[0].label;
}
if (apiData.kasus_percentage) {
const ctx = document.getElementById('stackedPNChart').getContext('2d');
// Ambil 10 teratas berdasarkan kontribusi_kasus
const top10 = apiData.kasus_percentage
.slice()
.sort((a, b) => Number(b.kontribusi_kasus) - Number(a.kontribusi_kasus))
.slice(0, 10);
const crimeLabels = top10.map(r => r.tindak_pidana);
// Kolom persentase yang tersedia
const percentageKeys = [
"penjara",
"penjara_seumur_hidup",
"denda",
"bebas_bersyarat",
"bebas_dakwaan",
"hukuman_mati",
].filter(k => top10[0].hasOwnProperty(k));
const colors = [
'#E57373', // soft red (selaras dengan max background)
'#81C784', // soft green (selaras dengan min background)
'#64B5F6', // soft light blue
'#FFB74D', // soft orange
'#BA68C8', // soft purple
'#4DB6AC', // soft teal
'#B0C4DE', // soft steel-blue (warna default kamu)
];
const kasusColumnLabels = {
"bebas_bersyarat": "Conditional Release",
"bebas_dakwaan": "Acquittal",
"denda": "Fine",
"hukuman_mati": "Death Penalty",
"penjara": "Imprisonment",
"penjara_seumur_hidup": "Life Imprisonment",
};
const datasets = percentageKeys.map((key, idx) => ({
label: kasusColumnLabels[key] || key.replace(/_/g, ' ').toUpperCase(),
data: top10.map(r => Number(r[key]) || 0),
backgroundColor: colors[idx],
borderWidth: 1
}));
if (allCharts.stackedPNChart) allCharts.stackedPNChart.destroy();
allCharts.stackedPNChart = new Chart(ctx, {
type: 'bar',
data: {
labels: crimeLabels,
datasets: datasets
},
options: {
indexAxis: 'y',
responsive: true,
scales: {
x: {
stacked: true,
max: 100,
ticks: {
callback: v => v + "%"
}
},
y: {
stacked: true
}
},
plugins: {
legend: { position: 'right' },
tooltip: {
callbacks: {
label: ctx => {
const raw = ctx.raw ?? 0;
if (raw <= 0) return null;
return `${ctx.dataset.label}: ${raw.toFixed(3)}%`;
}
}
}
}
}
});
}
kasusDataFull = apiData.kasus_percentage.slice();
kasusPage = 0;
renderKasusTablePage();
// Animasi saat scroll ke diagram
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.style.opacity = '1';
entry.target.style.transform = 'translateY(0)';
}
});
}, { threshold: 0.1 });
document.querySelectorAll('canvas').forEach(canvas => {
canvas.parentElement.style.opacity = '0';
canvas.parentElement.style.transform = 'translateY(30px)';
canvas.parentElement.style.transition = 'all 0.6s ease-out';
observer.observe(canvas.parentElement);
});
})
.catch(error => {
console.error('Error loading statistics:', error);
alert('Failed to load statistic data. Please refresh the page.');
});
}
function renderKasusTablePage() {
const head = document.getElementById("kasusHead");
const body = document.getElementById("kasusBody");
const pageInfo = document.getElementById("kasusPageInfo");
body.innerHTML = "";
const sorted = kasusDataFull
.slice()
.sort((a, b) => Number(b.kontribusi_kasus) - Number(a.kontribusi_kasus));
const start = kasusPage * kasusPerPage;
const end = start + kasusPerPage;
const pageData = sorted.slice(start, end);
if (pageData.length === 0) return;
// Mapping kolom → label tampilan
const kasusColumnLabels = {
"bebas_bersyarat": "Conditional Release (%)",
"bebas_dakwaan": "Acquittal (%)",
"denda": "Fine (%)",
"hukuman_mati": "Death Penalty (%)",
"kategori_pidana": "Category",
"kontribusi_kasus": "Case Contribution (%)",
"penjara": "Imprisonment (%)",
"penjara_seumur_hidup": "Life Imprisonment (%)",
"rata-rata_denda": "Average Fine (Rupiah)",
"rata-rata_penjara": "Average Imprisonment (Months)",
"penjara_seumur_hidup": "Life Imprisonment (%)",
"tindak_pidana": "Crime Action"
};
// === HEADER ===
head.innerHTML = "";
Object.keys(pageData[0]).forEach(col => {
const label = kasusColumnLabels[col] || col;
head.innerHTML += `<th>${label}</th>`;
});
// === BODY ===
pageData.forEach(row => {
let rowHTML = "<tr>";
Object.keys(row).forEach(col => {
let val = row[col];
if (typeof val === "number" && !Number.isInteger(val)) {
val = val.toFixed(3);
}
if (val === null || val === undefined || val === "") {
val = "-";
}
rowHTML += `<td>${val}</td>`;
});
rowHTML += "</tr>";
body.innerHTML += rowHTML;
});
const totalPages = Math.ceil(kasusDataFull.length / kasusPerPage);
pageInfo.innerText = `Page ${kasusPage + 1} / ${totalPages}`;
}
// Buttons
document.getElementById("prevKasus").onclick = function () {
if (kasusPage > 0) {
kasusPage--;
renderKasusTablePage();
}
};
document.getElementById("nextKasus").onclick = function () {
const totalPages = Math.ceil(kasusDataFull.length / kasusPerPage);
if (kasusPage < totalPages - 1) {
kasusPage++;
renderKasusTablePage();
}
};
// ================= GLOBAL PAGINATION STATE =================
let kasusPage = 0;
const kasusPerPage = 10;
let kasusDataFull = [];
// Load statistics on page load
loadStatistics('/api/statistics');
</script>
</body>
</html> |