handle missing elements in scripts, simplify stats page

This commit is contained in:
Tykayn 2025-06-01 18:56:01 +02:00 committed by tykayn
parent 1e30f360a1
commit 344e71d38f
9 changed files with 247 additions and 47 deletions

View file

@ -24,7 +24,7 @@
<i class="bi bi-chat-dots"></i> {{ stats.getAvecNote() }} commerces avec note renseignée.
<br>
</div>
<div id="map"></div>
<div class="card mt-4">
<h1 class="card-title">Tableau des commerces</h1>
<table class="table table-bordered">
@ -41,7 +41,7 @@
{% for commerce in stats.places %}
<tr>
<td style="background-color: {{ commerce.hasAddress() ? 'yellowgreen' : 'transparent' }};">
<a href="{{ path('app_admin_commerce', {'id': commerce.id}) }}">{{ commerce.name }}</a>
<a href="{{ path('app_admin_commerce', {'id': commerce.id}) }}"> {% if commerce.name |length %} {{ commerce.name |slice(0, 20) }}... {% else %} (lieu sans nom) {% endif %}</a>
</td>
<td style="background-color: {{ commerce.hasAddress() ? 'yellowgreen' : 'transparent' }};">{{ commerce.address }}</td>
@ -54,22 +54,88 @@
</table>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const headers = document.querySelectorAll('th');
headers.forEach(header => {
const text = header.textContent;
const match = text.match(/\((\d+)\s*\/\s*(\d+)\)/);
if (match) {
const [_, completed, total] = match;
const ratio = completed / total;
const alpha = ratio.toFixed(2);
header.style.backgroundColor = `rgba(154, 205, 50, ${alpha})`;
}
});
});
{% endblock %}
{% block javascripts %}
{{ parent() }}
<script src='https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.js'></script>
<script>
</script>
<style>
</style>
console.log('go faire une carte ');
const request = `[out:json][timeout:25];
area["postal_code"="{{ zip_code }}"]->.searchArea;
(
nw["amenity"]["cafe|bar|restaurant|library|cinema|fast_food"](area.searchArea);
nw["shop"](area.searchArea);
nw["tourism"="museum|hotel|chalet|apartment"](area.searchArea);
nw["office"](area.searchArea);
);
out center;
>;
out skel qt;
`;
document.addEventListener('DOMContentLoaded', function() {
async function fetchland() {
// Construire la requête Overpass
const encodedRequest = encodeURIComponent(request);
console.log('encodedRequest', encodedRequest);
const overpassUrl = `https://overpass-api.de/api/interpreter?data=${encodedRequest}`;
const response = await fetch(overpassUrl);
const data = await response.json();
console.log('data', data);
mapboxgl.accessToken = '{{ mapbox_token }}';
const map = new mapboxgl.Map({
container: 'map',
style: 'https://api.maptiler.com/maps/basic-v2/style.json?key={{ maptiler_token }}',
zoom: 17
});
// Ajouter les marqueurs pour chaque point
if (data.elements && data.elements.length > 0) {
const firstPoint = data.elements[0];
if (firstPoint.lat && firstPoint.lon) {
// Centrer la carte sur le premier point
map.setCenter([firstPoint.lon, firstPoint.lat]);
// Ajouter un marqueur pour le premier point
new mapboxgl.Marker()
.setLngLat([firstPoint.lon, firstPoint.lat])
.setPopup(new mapboxgl.Popup({ offset: 25 })
.setHTML(`<h3>${firstPoint.tags?.name || 'Sans nom'}</h3>`))
.addTo(map);
}
}
}
function colorizeHeaders() {
const headers = document.querySelectorAll('th');
if(headers.length > 0) {
headers.forEach(header => {
const text = header.textContent;
const match = text.match(/\((\d+)\s*\/\s*(\d+)\)/);
if (match) {
const [_, completed, total] = match;
const ratio = completed / total;
const alpha = ratio.toFixed(2);
header.style.backgroundColor = `rgba(154, 205, 50, ${alpha})`;
}
});
}
}
console.log(request);
colorizeHeaders();
fetchland();
})
</script>
{% endblock %}

View file

@ -13,9 +13,13 @@
<!-- JavaScript Bootstrap avec Popper.js -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
<link rel="icon" type="image/png" href="{{ asset('logo-osm.png') }}">
<!-- Script pour le tri automatique des tableaux -->
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
{# Run `composer require symfony/webpack-encore-bundle` to start using Symfony UX #}
{% block stylesheets %}
{{ encore_entry_link_tags('app') }}
<link href='https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.css' rel='stylesheet' />
{% endblock %}
</head>
<body>
@ -91,7 +95,7 @@
{% block javascripts %}
{{ encore_entry_script_tags('app') }}
<script src="{{ asset('js/main.js') }}"></script>
{# <script src="{{ asset('js/main.js') }}"></script> #}
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js" integrity="sha512-CNgIRecGo7nphbeZ04Sc13ka07paqdeTu0WR1IM4kNcpmBAUSHSQX0FslNhTDadL4O5SAGapGt4FodqL8My0mA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
new QRCode(document.getElementById('qrcode'), {
@ -102,6 +106,26 @@
colorLight : '#ffffff',
correctLevel : QRCode.CorrectLevel.H
});
// Tri automatique des tableaux
// Sélectionner la première table du document
if( Sortable) {
const firstTable = document.querySelector('table');
if (firstTable) {
console.log('première table trouvée', firstTable);
var sortable = new Sortable(firstTable, {
animation: 150,
ghostClass: 'sortable-ghost',
chosenClass: 'sortable-chosen',
dragClass: 'sortable-drag'
});
} else {
console.log('pas de table trouvée');
}
}else{
console.log('Sortable non trouvé');
}
</script>
{% endblock %}
</body>

View file

@ -14,10 +14,82 @@
{% block javascripts %}
{{ parent() }}
<script src='https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.js'></script>
<script>
function labourer() {
window.location.href = '/admin/labourer/' + document.getElementById('app_admin_labourer').value;
}
mapboxgl.accessToken = '{{ mapbox_token }}';
// Créer une carte des villes avec les codes postaux
let map = new mapboxgl.Map({
container: 'mapDashboard',
style: 'https://api.maptiler.com/maps/basic-v2/style.json?key={{ maptiler_token }}',
center: [2.3488, 48.8534], // Paris
zoom: 10
});
// Ajouter les marqueurs pour chaque zone
// Fonction pour récupérer tous les centroides des codes postaux en une seule requête
async function getAllPostalCodesCoordinates() {
const postalCodes = [{% for stat in stats %}'{{ stat.zone }}'{% if not loop.last %}, {% endif %}{% endfor %}];
const query = `[out:json];
(
${postalCodes.map(code => `
nwr["boundary"="postal_code"][postal_code=${code}];
);
out center;`;
console.log(query);
const response = await fetch('https://overpass-api.de/api/interpreter', {
method: 'POST',
body: query
});
const data = await response.json();
return data.elements.reduce((acc, element) => {
// On associe chaque code postal à ses coordonnées
const postalCode = element.tags.postal_code;
if (postalCode) {
acc[postalCode] = [element.lon, element.lat];
}
return acc;
}, {});
}
// Fonction pour obtenir la couleur selon le pourcentage
function getColorFromPercent(percent) {
const red = Math.round(255 * (1 - percent/100));
const green = Math.round(255 * (percent/100));
return `rgb(${red}, ${green}, 0)`;
}
// On récupère toutes les coordonnées en une seule fois
getAllPostalCodesCoordinates().then(coordinatesMap => {
{% for stat in stats %}
{% if not "-" in stat.zone %}
const coordinatesMapped{{ stat.zone }} = coordinatesMap['{{ stat.zone }}'];
if (coordinatesMapped{{ stat.zone }}) {
const el = document.createElement('div');
el.style.width = '20px';
el.style.height = '20px';
el.style.borderRadius = '50%';
el.style.backgroundColor = getColorFromPercent({{ stat.completionPercent }});
new mapboxgl.Marker(el)
.setLngLat(coordinatesMapped{{ stat.zone }})
.setPopup(new mapboxgl.Popup().setHTML(`
<h3>{{ stat.zone }}</h3>
<p>Nombre de commerces: {{ stat.placesCount }}</p>
<p>Complétude: {{ stat.completionPercent }}%</p>
`))
.addTo(map);
}
{% endif %}
{% endfor %}
});
</script>
{% endblock %}
@ -29,9 +101,10 @@
</div>
<div class="col-12">
<h2>Statistiques : {{ stats|length }} commerces</h2>
<input class="form-control" type="text" id="app_admin_labourer" value="75013">
<button class="btn btn-default" onclick="labourer() ">Labourer</button>
mapDashboard:
<div id="mapDashboard"></div>
<input class="form-control" type="text" id="app_admin_labourer" value="75013">
<button class="btn btn-default" onclick="labourer() ">Labourer</button>
<table class="table table-hover table-striped table-responsive">
@ -61,7 +134,8 @@
</tbody>
</table>
<h2>Lieux</h2>
<h2>{{ places|length }} Lieux</h2>
{#
<table class="table table-striped table-hover table-responsive">
<thead>
<tr>
@ -104,7 +178,8 @@
</tr>
{% endfor %}
</tbody>
</table>
</table>
#}
</div>
</div>
</div>

View file

@ -4,7 +4,6 @@
{% block stylesheets %}
{{ parent() }}
<link href='https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.css' rel='stylesheet' />
<style>
.hidden { display: none; }
input[type="checkbox"] { width: 20px; height: 20px; }
@ -216,18 +215,18 @@
}
{% if commerce is not empty and mapbox_token is not empty and maptiler_token is not empty and commerce_overpass['@attributes'].lon is defined and commerce_overpass['@attributes'].lat is defined %}
mapboxgl.accessToken = '{{ mapbox_token }}';
map = new mapboxgl.Map({
container: 'map',
style: 'https://api.maptiler.com/maps/basic-v2/style.json?key={{ maptiler_token }}',
center: [{{ commerce_overpass['@attributes'].lon }}, {{ commerce_overpass['@attributes'].lat }}],
zoom: 17
});
mapboxgl.accessToken = '{{ mapbox_token }}';
map = new mapboxgl.Map({
container: 'map',
style: 'https://api.maptiler.com/maps/basic-v2/style.json?key={{ maptiler_token }}',
center: [{{ commerce_overpass['@attributes'].lon }}, {{ commerce_overpass['@attributes'].lat }}],
zoom: 17
});
new mapboxgl.Marker()
.setLngLat([{{ commerce_overpass['@attributes'].lon }}, {{ commerce_overpass['@attributes'].lat }}])
.setPopup(new mapboxgl.Popup({ offset: 25 }).setHTML('<h1>{{ commerce_overpass.tags_converted.name }}</h1>'))
.addTo(map);
new mapboxgl.Marker()
.setLngLat([{{ commerce_overpass['@attributes'].lon }}, {{ commerce_overpass['@attributes'].lat }}])
.setPopup(new mapboxgl.Popup({ offset: 25 }).setHTML('<h1>{{ commerce_overpass.tags_converted.name }}</h1><p>Completion:{{completion_percentage}}%</p>'))
.addTo(map);
{% endif %}
</script>