osm-commerces/templates/admin/stats.html.twig
2025-06-26 23:14:22 +02:00

640 lines
25 KiB
Twig

{% extends 'base.html.twig' %}
{% block title %}{{ 'display.stats'|trans }}- {{ stats.zone }}
{{ stats.name }} {% endblock %}
{% block stylesheets %}
{{ parent() }}
<link href='{{ asset('js/maplibre/maplibre-gl.css') }}' rel='stylesheet' />
<style>
.completion-circle {
fill-opacity: 0.6;
stroke: #fff;
stroke-width: 3;
}
#distribution_completion {
height: 300px;
margin: 20px 0;
}
.completion-info {
margin-bottom: 2rem;
}
.osm-modification-info {
font-size: 0.85rem;
line-height: 1.3;
}
.osm-modification-info .text-muted {
font-size: 0.75rem;
}
.osm-modification-info a {
text-decoration: none;
color: #0d6efd;
}
.osm-modification-info a:hover {
text-decoration: underline;
}
.osm-freshness-info {
font-size: 0.95rem;
line-height: 1.4;
}
.osm-freshness-info .alert {
border-left: 4px solid #0dcaf0;
background-color: #f8f9fa;
}
</style>
{% endblock %}
{% block body %}
<div class="container">
<div class="mt-4 p-4">
<div class="row">
<div class="col-md-6 col-12">
<h1 class="title">{{ 'display.stats'|trans }} - {{ stats.zone }}
{{ stats.name }} - {{ stats.completionPercent }}% complété</h1>
</div>
<div class="col-md-6 col-12">
<a href="{{ path('app_admin_labourer', {'insee_code': stats.zone, 'deleteMissing': 1}) }}" class="btn btn-primary" id="labourer">Labourer les mises à jour</a>
<button id="openInJOSM" class="btn btn-secondary ms-2">
<i class="bi bi-map"></i> Ouvrir dans JOSM
</button>
</div>
</div>
{% if stats.population %}
<div class="row mb-3">
<div class="col-md-4 col-12">
<span class="badge bg-info">
<i class="bi bi-people"></i> Population&nbsp;: {{ stats.population|number_format(0, '.', ' ') }}
</span>
</div>
<div class="col-md-4 col-12">
<span class="badge bg-secondary">
<i class="bi bi-shop"></i> 1 lieu pour
{% set ratio = (stats.population and stats.places|length > 0) ? (stats.population / stats.places|length)|round(0, 'ceil') : '?' %}
{{ ratio|number_format(0, '.', ' ') }} habitants
</span>
</div>
<div class="col-md-4 col-12">
<span class="badge bg-success">
<i class="bi bi-pencil-square"></i> {{ stats.getAvecNote() }} / {{ stats.places|length }} lieux avec note
</span>
</div>
</div>
{% if stats.budgetAnnuel %}
<div class="row mb-3">
<div class="col-md-4 col-12">
<span class="badge bg-warning text-dark">
<i class="bi bi-cash-coin"></i> Budget annuel&nbsp;: {{ stats.budgetAnnuel|number_format(0, '.', ' ') }}
</span>
</div>
<div class="col-md-4 col-12">
<span class="badge bg-warning text-dark">
<i class="bi bi-cash-stack"></i> Budget par habitant&nbsp;:
{% if stats.population > 0 %}
{{ (stats.budgetAnnuel / stats.population)|number_format(0, '.', ' ') }}
{% else %}
?
{% endif %}
</span>
</div>
</div>
{% endif %}
{% endif %}
<div class="row">
<div class="col-md-3 col-12">
<span class="badge {% if stats.getCompletionPercent() > 85 %}bg-success{% else %}bg-warning{% endif %}">
{{ stats.getCompletionPercent() }} %
</span>
complété sur les critères donnés.
</div>
<div class="col-md-3 col-12">
<span class="badge bg-primary">
<i class="bi bi-building"></i> {{ stats.places | length}}
</span>lieux dans la zone.
</div>
<div class="col-md-3 col-12">
<span class="badge bg-primary">
<i class="bi bi-clock"></i> {{ stats.getAvecHoraires() }}
</span>
lieux avec horaires.
</div>
<div class="col-md-3 col-12">
<span class="badge bg-primary">
<i class="bi bi-map"></i> {{ stats.getAvecAdresse() }}
</span>
lieux avec adresse.
</div>
<div class="col-md-3 col-12">
<span class="badge bg-primary">
<i class="bi bi-globe"></i> {{ stats.getAvecSite() }}
</span>
lieux avec site web renseigné.
</div>
<div class="col-md-3 col-12">
<span class="badge bg-primary">
<i class="bi bi-arrow-up-right"></i>
{{ stats.getAvecAccessibilite() }}
</span>
lieux avec accessibilité PMR renseignée.
</div>
<div class="col-md-3 col-12">
<span class="badge bg-primary">
<i class="bi bi-chat-dots"></i> {{ stats.getAvecNote() }}
</span>
lieux avec note renseignée.
</div>
</div>
<div id="maploader">
<div class="spinner-border" role="status">
<i class="bi bi-load bi-spin"></i>
<span class="visually-hidden">Chargement de la carte...</span>
</div>
</div>
<div class="d-flex justify-content-end mb-2">
<div class="btn-group" role="group">
<button type="button" class="btn btn-outline-primary" id="circleMarkersBtn">
<i class="bi bi-circle"></i> Cercles
</button>
<button type="button" class="btn btn-outline-primary active" id="dropMarkersBtn">
<i class="bi bi-geo-alt"></i> Gouttes
</button>
</div>
</div>
<div id="map" style="height: 400px; width: 100%; margin-bottom: 1rem;"></div>
<div class="row ">
<div class="col-md-6 col-12 ">
<canvas id="repartition_tags" width="600" height="300" style="max-width:100%; margin: 20px 0;"></canvas>
</div>
<div class="col-md-6 col-12 ">
<div class="card">
<div class="card-header">
<i class="bi bi-calendar-event"></i> Fréquence des mises à jour par trimestre pour {{stats.name}}
</div>
<div class="card-body">
<canvas id="modificationsByQuarterChart" style="min-height: 250px; width: 100%;"></canvas>
</div>
</div>
</div>
</div>
<div id="attribution">
<a href="https://www.openstreetmap.org/copyright">Données OpenStreetMap</a>
</div>
</div>
<div class="card mt-4">
{% include 'admin/stats_history.html.twig' with {stat: stats} %}
<canvas id="distribution_completion" class="mt-4 mb-4" height="600"></canvas>
<div class="row">
<div class="col-md-6 col-12">
<h1 class="card-title p-4">Tableau des {{ stats.places |length }} lieux</h1>
</div>
<div class="col-md-6 col-12">
<a class="btn btn-primary pull-right mt-4" href="{{ path('app_admin_export_csv', {'insee_code': stats.zone}) }}" class="btn btn-primary">
<i class="bi bi-filetype-csv"></i>
Exporter en CSV
</a>
</div>
</div>
{# <input type="text" id="stats-table-search" class="form-control mb-2" placeholder="Filtrer les lieux..."> #}
<table id="stats-table" class="table table-bordered table-striped table-hover table-responsive table-sort">
{% include 'admin/stats/table-head.html.twig' %}
<tbody>
{% for commerce in stats.places %}
{% include 'admin/stats/row.html.twig' %}
{% endfor %}
</tbody>
</table>
</div>
{# <div class="card mt-4">
<div class="card-header">
<h2>Requête Overpass</h2>
<div id=overPassRequest >
<pre>
{{overpass}}
</pre>
</div>
</div>
</div> #}
<div class="completion-info mt-4">
<div class="alert alert-info">
<div class="d-flex align-items-center completion-hover-trigger" style="cursor: pointer;">
<i class="bi bi-info-circle me-2"></i>
<p class="mb-0">Comment est calculé le score de complétion ?</p>
<i class="bi bi-chevron-down ms-auto" id="completionInfoIcon"></i>
</div>
<div id="completionInfoContent" style="display: none;" class="mt-3">
<p>Le score de complétion est calculé en fonction de plusieurs critères :</p>
<ul>
<li>Nom du commerce</li>
<li>Adresse complète (numéro, rue, code postal)</li>
<li>Horaires d'ouverture</li>
<li>Site web</li>
<li>Numéro de téléphone</li>
<li>Accessibilité PMR</li>
</ul>
<p>Chaque critère rempli augmente le score de complétion d'une part égale.
Un commerce parfaitement renseigné aura un score de 100%.</p>
</div>
</div>
</div>
<div class="accordion mb-3" id="accordionStats">
<div class="accordion-item">
<h2 class="accordion-header" id="headingOne">
</div>
</div>
<!-- Bouton caché pour JOSM -->
<a id="josmButton" style="display: none;"></a>
{% endblock %}
{% block javascripts %}
{{ parent() }}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
const geojsonData = {{ geojson|raw }};
const map_token = "{{ maptiler_token }}";
let map;
let map_is_loaded = false;
let currentMode = 'drop';
// Fonction pour mettre à jour le style des marqueurs
window.updateMarkers = function(mode) {
currentMode = mode;
// Mettre à jour l'état visuel des boutons
document.getElementById('circleMarkersBtn').classList.toggle('active', mode === 'circle');
document.getElementById('dropMarkersBtn').classList.toggle('active', mode === 'drop');
if (!map) return;
// Supprimer la couche si elle existe déjà
if (map.getLayer('unclustered-point')) {
map.removeLayer('unclustered-point');
}
// Ajouter la couche selon le mode
if (mode === 'circle') {
map.addLayer({
id: 'unclustered-point',
type: 'circle',
source: 'places',
filter: ['!', ['has', 'point_count']],
paint: {
'circle-color': [
'case',
['has', 'completion'],
[
'rgb',
['-', 255, ['*', ['get', 'completion'], 2.55]],
['*', ['get', 'completion'], 2.55],
80
],
'#cccccc'
],
'circle-radius': 10,
'circle-stroke-width': 2,
'circle-stroke-color': '#fff'
}
});
} else {
map.addLayer({
id: 'unclustered-point',
type: 'circle',
source: 'places',
filter: ['!', ['has', 'point_count']],
paint: {
'circle-color': '#11b4da',
'circle-radius': 8,
'circle-stroke-width': 2,
'circle-stroke-color': '#fff'
}
});
}
}
if (map_token && geojsonData && geojsonData.features.length > 0) {
map = new maplibregl.Map({
container: 'map',
style: `https://api.maptiler.com/maps/streets/style.json?key=${map_token}`,
center: geojsonData.features[0].geometry.coordinates,
zoom: 14
});
map.on('load', function() {
map_is_loaded = true;
document.getElementById('maploader').style.display = 'none';
map.addSource('places', {
type: 'geojson',
data: geojsonData,
cluster: true,
clusterMaxZoom: 14,
clusterRadius: 50
});
map.addLayer({
id: 'clusters',
type: 'circle',
source: 'places',
filter: ['has', 'point_count'],
paint: {
'circle-color': [
'step', ['get', 'point_count'],
'#51bbd6', 100,
'#f1f075', 750,
'#f28cb1'
],
'circle-radius': [
'step', ['get', 'point_count'],
20, 100,
30, 750,
40
]
}
});
map.addLayer({
id: 'cluster-count',
type: 'symbol',
source: 'places',
filter: ['has', 'point_count'],
layout: {
'text-field': '{point_count_abbreviated}',
'text-font': ['DIN Offc Pro Medium', 'Arial Unicode MS Bold'],
'text-size': 12
}
});
// Par défaut, gouttes bleues
window.updateMarkers('drop');
// Listeners boutons
document.getElementById('circleMarkersBtn').addEventListener('click', function() {
window.updateMarkers('circle');
});
document.getElementById('dropMarkersBtn').addEventListener('click', function() {
window.updateMarkers('drop');
});
// Popups et clusters (inchangé)
map.on('click', 'clusters', function(e) {
const features = map.queryRenderedFeatures(e.point, { layers: ['clusters'] });
const clusterId = features[0].properties.cluster_id;
map.getSource('places').getClusterExpansionZoom(clusterId, function(err, zoom) {
if (err) return;
map.easeTo({
center: features[0].geometry.coordinates,
zoom: zoom
});
});
});
map.on('click', 'unclustered-point', function(e) {
const coordinates = e.features[0].geometry.coordinates.slice();
const properties = e.features[0].properties;
let popupContent = `<strong>${properties.name || 'Sans nom'}</strong><br>`;
if (properties.address) popupContent += `${properties.address}<br>`;
if (properties.main_tag) popupContent += `<em>${properties.main_tag}</em><br>`;
if (properties.note) popupContent += `<small>Note: ${properties.note}</small><br>`;
popupContent += `<a href="${properties.osm_url}" target="_blank">Voir sur OSM</a>`;
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
new maplibregl.Popup()
.setLngLat(coordinates)
.setHTML(popupContent)
.addTo(map);
});
map.on('mouseenter', 'clusters', function() {
map.getCanvas().style.cursor = 'pointer';
});
map.on('mouseleave', 'clusters', function() {
map.getCanvas().style.cursor = '';
});
});
} else {
const mapDiv = document.getElementById('map');
if (mapDiv) {
mapDiv.innerHTML = '<div class="alert alert-warning">Aucune donnée géographique à afficher pour cette zone.</div>';
}
document.getElementById('maploader').style.display = 'none';
}
const openInJOSMButton = document.getElementById('openInJOSM');
if (openInJOSMButton) {
openInJOSMButton.addEventListener('click', () => {
const osmElements = geojsonData.features.map(f => ({
osm_id: f.properties.id.split('/')[1],
osm_type: f.properties.id.split('/')[0]
}));
openInJOSM(map, map_is_loaded, osmElements);
});
}
// === GRAPHIQUE FRÉQUENCE DES MISES À JOUR PAR TRIMESTRE ===
const modifData = {{ modificationsByQuarter|raw }};
const modifLabels = Object.keys(modifData);
const modifCounts = Object.values(modifData);
const modifCanvas = document.getElementById('modificationsByQuarterChart');
if (modifCanvas && modifLabels.length > 0) {
new Chart(modifCanvas.getContext('2d'), {
type: 'bar',
data: {
labels: modifLabels,
datasets: [{
label: 'Nombre de lieux modifiés',
data: modifCounts,
backgroundColor: 'rgba(54, 162, 235, 0.7)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
},
options: {
responsive: true,
plugins: {
legend: { display: false },
title: { display: true, text: 'Fréquence des mises à jour par trimestre' }
},
scales: {
y: { beginAtZero: true, title: { display: true, text: 'Nombre de lieux' } },
x: { title: { display: true, text: 'Trimestre' } }
}
}
});
} else if (modifCanvas) {
modifCanvas.parentNode.innerHTML = '<div class="alert alert-info">Aucune donnée de modification disponible pour cette ville.</div>';
}
// Créer un graphique de la répartition des tags
const tagsCount = {};
const places = {{ geojson|raw }}.features;
places.forEach(place => {
const mainTag = place.properties.main_tag;
if (mainTag) {
tagsCount[mainTag] = (tagsCount[mainTag] || 0) + 1;
}
});
const sortedTags = Object.entries(tagsCount).sort(([, a], [, b]) => b - a);
const labels = sortedTags.map(item => item[0]);
const data = sortedTags.map(item => item[1]);
const container_tags= document.getElementById('repartition_tags');
console.log('répartition', tagsCount, container_tags)
if(!container_tags){
console.log('pas de container_tags', container_tags)
return;
}
const ctx = container_tags.getContext ? container_tags.getContext('2d') : null;
if(ctx){
new Chart(ctx, {
type: 'doughnut',
data: {
labels: labels,
datasets: [{
label: 'Répartition des tags',
data: data,
backgroundColor: [
'rgba(54, 162, 235, 0.7)',
'rgba(255, 99, 132, 0.7)',
'rgba(255, 206, 86, 0.7)',
'rgba(75, 192, 192, 0.7)',
'rgba(153, 102, 255, 0.7)',
'rgba(255, 159, 64, 0.7)',
'rgba(201, 203, 207, 0.7)'
],
borderColor: [
'rgba(54, 162, 235, 1)',
'rgba(255, 99, 132, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
'rgba(201, 203, 207, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'right',
},
title: {
display: true,
text: 'Répartition des tags principaux'
}
}
}
});
}
// Graphique de distribution du taux de complétion
const completionData = [];
{% for commerce in stats.places %}
completionData.push({{ commerce.getCompletionPercentage() }});
{% endfor %}
const completionDistribution = {};
completionData.forEach(percent => {
const range = Math.floor(percent / 10) * 10;
const key = `${range}-${range + 10}%`;
completionDistribution[key] = (completionDistribution[key] || 0) + 1;
});
const completionLabels = Object.keys(completionDistribution).sort((a, b) => {
return parseInt(a.split('-')[0]) - parseInt(b.split('-')[0]);
});
const completionValues = completionLabels.map(label => completionDistribution[label]);
const dc = document.getElementById('distribution_completion');
if(dc ){
const completionCtx = dc.getContext ? dc.getContext('2d') : null;
if(!completionCtx){
console.log('pas de completionCtx' )
return ;
}
new Chart(completionCtx, {
type: 'line',
data: {
labels: completionLabels,
datasets: [{
label: 'Distribution du Taux de Complétion',
data: completionValues,
backgroundColor: 'rgba(75, 192, 192, 0.5)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
},
responsive: true,
}
});
}else{
console.log('pas de distribution_completion')
}
});
</script>
<script>
document.addEventListener('DOMContentLoaded', function() {
const trigger = document.querySelector('.completion-hover-trigger');
const content = document.getElementById('completionInfoContent');
const icon = document.getElementById('completionInfoIcon');
if (trigger && content) {
trigger.addEventListener('mouseenter', function() {
content.style.display = 'block';
if (icon) {
icon.classList.remove('bi-chevron-down');
icon.classList.add('bi-chevron-up');
}
});
trigger.addEventListener('mouseleave', function() {
content.style.display = 'none';
if (icon) {
icon.classList.remove('bi-chevron-up');
icon.classList.add('bi-chevron-down');
}
});
// Pour garder la popup ouverte si la souris va sur la popup
content.addEventListener('mouseenter', function() {
content.style.display = 'block';
});
content.addEventListener('mouseleave', function() {
content.style.display = 'none';
if (icon) {
icon.classList.remove('bi-chevron-up');
icon.classList.add('bi-chevron-down');
}
});
}
});
</script>
{% endblock %}