saufen/templates/components/history_chart.html.twig

123 lines
4.6 KiB
Twig

{#
History Chart Component
Parameters:
- stock_history: Array of stock history records with changeDate and newValue properties
- wanted_history: Array of wanted stock history records with newValue properties
- chart_id: ID for the canvas element (default: 'stockHistoryChart')
- title: Title for the chart card (default: 'History')
#}
{% set chart_id = chart_id|default('stockHistoryChart') %}
{% set title = title|default('History') %}
<div class="card">
<div class="card-header">
<h5 class="card-title">{{ title }}</h5>
</div>
<div class="card-body">
<div style="height: 300px; position: relative;">
<canvas id="{{ chart_id }}"></canvas>
</div>
<script type="module">
import { Chart } from 'chart.js/auto';
// Create a unified set of dates from both datasets
{% set all_dates = [] %}
{% for record in stock_history %}
{% set date_str = record.changeDate|date('Y-m-d H:i') %}
{% if date_str not in all_dates %}
{% set all_dates = all_dates|merge([date_str]) %}
{% endif %}
{% endfor %}
{% for record in wanted_history %}
{% set date_str = record.changeDate|date('Y-m-d H:i') %}
{% if date_str not in all_dates %}
{% set all_dates = all_dates|merge([date_str]) %}
{% endif %}
{% endfor %}
// Sort dates chronologically
{% set all_dates = all_dates|sort %}
// Create date-indexed maps for both datasets
{% set stock_map = {} %}
{% for record in stock_history %}
{% set date_str = record.changeDate|date('Y-m-d H:i') %}
{% set stock_map = stock_map|merge({(date_str): record.newValue}) %}
{% endfor %}
{% set wanted_map = {} %}
{% for record in wanted_history %}
{% set date_str = record.changeDate|date('Y-m-d H:i') %}
{% set wanted_map = wanted_map|merge({(date_str): record.newValue}) %}
{% endfor %}
// Prepare data arrays with values aligned to dates
{% set stock_data = [] %}
{% set wanted_data = [] %}
{% for date in all_dates %}
{% if date in stock_map|keys %}
{% set stock_data = stock_data|merge([stock_map[date]]) %}
{% else %}
{% set stock_data = stock_data|merge(['null']) %}
{% endif %}
{% if date in wanted_map|keys %}
{% set wanted_data = wanted_data|merge([wanted_map[date]]) %}
{% else %}
{% set wanted_data = wanted_data|merge(['null']) %}
{% endif %}
{% endfor %}
new Chart(document.getElementById('{{ chart_id }}'), {
type: 'line',
data: {
labels: [{% for date in all_dates %}'{{ date }}'{{ not loop.last ? ',' }}{% endfor %}],
datasets: [{
label: 'Stock History',
data: [{{ stock_data|join(',') }}],
borderColor: 'rgb(75, 192, 192)',
tension: 0.1,
spanGaps: true
},
{
label: 'Wanted Stock History',
data: [{{ wanted_data|join(',') }}],
borderColor: 'rgb(255, 99, 132)',
tension: 0.1,
spanGaps: true
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'top',
labels: {
boxWidth: 12,
padding: 10
}
}
},
scales: {
y: {
beginAtZero: true,
ticks: {
maxTicksLimit: 6
}
},
x: {
ticks: {
maxTicksLimit: 8,
maxRotation: 45
}
}
}
}
});
</script>
</div>
</div>