thèmes en plus, graph embed

This commit is contained in:
Tykayn 2025-06-30 15:03:37 +02:00 committed by tykayn
parent 4300278f15
commit f4e8c70ead
7 changed files with 327 additions and 9 deletions

View file

@ -260,18 +260,32 @@ final class AdminController extends AbstractController
]);
}
#[Route('/admin/stats/{insee_code}', name: 'app_admin_stats')]
public function calculer_stats(string $insee_code): Response
#[Route('/admin/stats/{insee_code}', name: 'app_admin_stats', requirements: ['insee_code' => '\\d+'])]
public function stats(string $insee_code): Response
{
// Récupérer les stats existantes pour la zone
$stats = $this->entityManager->getRepository(Stats::class)->findOneBy(['zone' => $insee_code]);
if (!$stats) {
// Si aucune statistique n'existe pour cette zone, rediriger vers le labourage de la zone
return $this->redirectToRoute('app_admin_labourer', ['insee_code' => $insee_code]);
$this->addFlash('error', 'Aucune stats trouvée pour ce code INSEE.');
return $this->redirectToRoute('app_admin');
}
// Si aucun followup n'existe, on les régénère automatiquement
if ($stats->getCityFollowUps()->isEmpty()) {
$followups = $stats->getCityFollowUps();
$refresh = false;
if (!$followups->isEmpty()) {
$latest = null;
foreach ($followups as $fu) {
if ($latest === null || $fu->getDate() > $latest->getDate()) {
$latest = $fu;
}
}
if ($latest && $latest->getDate() < (new \DateTime('-1 day'))) {
$refresh = true;
}
} else {
$refresh = true;
}
if ($refresh) {
$this->followUpService->generateCityFollowUps($stats, $this->motocultrice, $this->entityManager);
$followups = $stats->getCityFollowUps();
}
$commerces = $stats->getPlaces();
$this->actionLogger->log('stats_de_ville', ['insee_code' => $insee_code, 'nom' => $stats->getZone()]);

View file

@ -65,7 +65,21 @@ class FollowUpController extends AbstractController
return $this->redirectToRoute('app_admin');
}
$followups = $stats->getCityFollowUps();
if ($followups->isEmpty()) {
$refresh = false;
if (!$followups->isEmpty()) {
$latest = null;
foreach ($followups as $fu) {
if ($latest === null || $fu->getDate() > $latest->getDate()) {
$latest = $fu;
}
}
if ($latest && $latest->getDate() < (new \DateTime('-1 day'))) {
$refresh = true;
}
} else {
$refresh = true;
}
if ($refresh) {
$this->followUpService->generateCityFollowUps($stats, $motocultrice, $em);
$followups = $stats->getCityFollowUps();
}
@ -148,4 +162,56 @@ class FollowUpController extends AbstractController
'followup_overpass' => FollowUpService::getFollowUpOverpassQueries(),
]);
}
#[Route('/admin/followup/{insee_code}/embed/{theme}', name: 'admin_followup_embed_graph', requirements: ['insee_code' => '\\d+', 'theme' => '[a-zA-Z0-9_]+'])]
public function followupEmbedGraph(
string $insee_code,
string $theme,
EntityManagerInterface $em,
Motocultrice $motocultrice
) {
$stats = $em->getRepository(Stats::class)->findOneBy(['zone' => $insee_code]);
if (!$stats) {
$this->addFlash('error', 'Aucune stats trouvée pour ce code INSEE.');
return $this->redirectToRoute('app_admin');
}
$followups = $stats->getCityFollowUps();
$refresh = false;
if (!$followups->isEmpty()) {
$latest = null;
foreach ($followups as $fu) {
if ($latest === null || $fu->getDate() > $latest->getDate()) {
$latest = $fu;
}
}
if ($latest && $latest->getDate() < (new \DateTime('-1 day'))) {
$refresh = true;
}
} else {
$refresh = true;
}
if ($refresh) {
$this->followUpService->generateCityFollowUps($stats, $motocultrice, $em);
$followups = $stats->getCityFollowUps();
}
$followups = $followups->toArray();
usort($followups, fn($a, $b) => $a->getDate() <=> $b->getDate());
$series = [];
foreach ($followups as $fu) {
if (str_starts_with($fu->getName(), $theme)) {
$series[$fu->getName()][] = [
'date' => $fu->getDate()->format('c'),
'value' => $fu->getMeasure(),
'name' => $fu->getName(),
];
}
}
return $this->render('admin/followup_embed_graph.html.twig', [
'stats' => $stats,
'series' => $series,
'theme' => $theme,
'label' => FollowUpService::getFollowUpThemes()[$theme] ?? $theme,
'icon' => FollowUpService::getFollowUpIcons()[$theme] ?? 'bi-question-circle',
]);
}
}

View file

@ -48,6 +48,22 @@ class FollowUpService
}) ?? [];
} elseif ($type === 'bicycle_parking') {
$objects = array_filter($elements, fn($el) => ($el['tags']['amenity'] ?? null) === 'bicycle_parking') ?? [];
} elseif ($type === 'advertising_board') {
$objects = array_filter($elements, fn($el) => ($el['tags']['advertising'] ?? null) === 'board' && ($el['tags']['message'] ?? null) === 'political') ?? [];
} elseif ($type === 'building') {
$objects = array_filter($elements, fn($el) => ($el['type'] ?? null) === 'way' && !empty($el['tags']['building'])) ?? [];
} elseif ($type === 'email') {
$objects = array_filter($elements, fn($el) => !empty($el['tags']['email'] ?? null) || !empty($el['tags']['contact:email'] ?? null)) ?? [];
} elseif ($type === 'bench') {
$objects = array_filter($elements, fn($el) => ($el['tags']['amenity'] ?? null) === 'bench') ?? [];
} elseif ($type === 'waste_basket') {
$objects = array_filter($elements, fn($el) => ($el['tags']['amenity'] ?? null) === 'waste_basket') ?? [];
} elseif ($type === 'street_lamp') {
$objects = array_filter($elements, fn($el) => ($el['tags']['highway'] ?? null) === 'street_lamp') ?? [];
} elseif ($type === 'drinking_water') {
$objects = array_filter($elements, fn($el) => ($el['tags']['amenity'] ?? null) === 'drinking_water') ?? [];
} elseif ($type === 'tree') {
$objects = array_filter($elements, fn($el) => ($el['tags']['natural'] ?? null) === 'tree') ?? [];
} elseif ($type === 'places') {
$objects = [];
} else {
@ -128,6 +144,43 @@ class FollowUpService
$completed = array_filter($data['objects'], function($el) {
return !empty($el['tags']['capacity'] ?? null) || !empty($el['tags']['covered'] ?? null);
});
} elseif ($type === 'advertising_board') {
$completed = array_filter($data['objects'], function($el) {
// On considère complet si le tag "operator" ou "ref" est présent
return !empty($el['tags']['operator'] ?? null) || !empty($el['tags']['ref'] ?? null);
});
} elseif ($type === 'building') {
$completed = array_filter($data['objects'], function($el) {
// Complet si ref:FR:RNB est rempli
return !empty($el['tags']['ref:FR:RNB'] ?? null);
});
} elseif ($type === 'email') {
$completed = $data['objects']; // Possède déjà un email ou contact:email
} elseif ($type === 'bench') {
$completed = array_filter($data['objects'], function($el) {
// Complet si le tag "material" ou "backrest" est présent
return !empty($el['tags']['material'] ?? null) || !empty($el['tags']['backrest'] ?? null);
});
} elseif ($type === 'waste_basket') {
$completed = array_filter($data['objects'], function($el) {
// Complet si le tag "material" ou "ref" est présent
return !empty($el['tags']['material'] ?? null) || !empty($el['tags']['ref'] ?? null);
});
} elseif ($type === 'street_lamp') {
$completed = array_filter($data['objects'], function($el) {
// Complet si le tag "lamp_type" ou "ref" est présent
return !empty($el['tags']['lamp_type'] ?? null) || !empty($el['tags']['ref'] ?? null);
});
} elseif ($type === 'drinking_water') {
$completed = array_filter($data['objects'], function($el) {
// Complet si le tag "covered" ou "ref" est présent
return !empty($el['tags']['covered'] ?? null) || !empty($el['tags']['ref'] ?? null);
});
} elseif ($type === 'tree') {
$completed = array_filter($data['objects'], function($el) {
// Complet si le tag "species" ou "ref" est présent
return !empty($el['tags']['species'] ?? null) || !empty($el['tags']['ref'] ?? null);
});
}
if ($type === 'lieux') {
// Si le type est "lieux", on utilise la méthode completionPercent() de $stats
@ -251,6 +304,14 @@ class FollowUpService
'police' => 'Commissariats',
'healthcare' => 'Lieux de santé',
'bicycle_parking' => 'Parkings vélos',
'advertising_board' => 'Panneaux électoraux',
'building' => 'Bâtiments',
'email' => 'Objets avec email',
'bench' => 'Bancs',
'waste_basket' => 'Poubelles',
'street_lamp' => 'Lampadaires',
'drinking_water' => 'Eau potable',
'tree' => 'Arbres',
'places' => 'Lieux'
];
}
@ -271,6 +332,14 @@ class FollowUpService
'police' => 'bi-shield-lock',
'healthcare' => 'bi-hospital',
'bicycle_parking' => 'bi-bicycle',
'advertising_board' => 'bi-easel',
'building' => 'bi-building',
'email' => 'bi-envelope-at',
'bench' => 'bi-badge-wc',
'waste_basket' => 'bi-trash',
'street_lamp' => 'bi-lightbulb',
'drinking_water' => 'bi-droplet-half',
'tree' => 'bi-tree',
'places' => 'bi-geo-alt'
];
}
@ -291,6 +360,14 @@ class FollowUpService
'police' => 'nwr["amenity"="police"](area.searchArea);',
'healthcare' => 'nwr["healthcare"](area.searchArea);nwr["amenity"="doctors"](area.searchArea);nwr["amenity"="pharmacy"](area.searchArea);nwr["amenity"="hospital"](area.searchArea);nwr["amenity"="clinic"](area.searchArea);nwr["amenity"="social_facility"](area.searchArea);',
'bicycle_parking' => 'nwr["amenity"="bicycle_parking"](area.searchArea);',
'advertising_board' => 'nwr["advertising"="board"]["message"="political"](area.searchArea);',
'building' => 'way["building"](area.searchArea);',
'email' => 'nwr["email"](area.searchArea);nwr["contact:email"](area.searchArea);',
'bench' => 'nwr["amenity"="bench"](area.searchArea);',
'waste_basket' => 'nwr["amenity"="waste_basket"](area.searchArea);',
'street_lamp' => 'nwr["highway"="street_lamp"](area.searchArea);',
'drinking_water' => 'nwr["amenity"="drinking_water"](area.searchArea);',
'tree' => 'nwr["natural"="tree"](area.searchArea);',
'places' => ''
];
}

View file

@ -11,7 +11,7 @@ class Motocultrice
public $overpass_base_places = '
(
nw["amenity"~"^(cafe|bar|restaurant|library|cinema|fast_food|post_office|marketplace|community_centre|theatre|bank|townhall|animal_boarding|animal_breeding|animal_shelter|animal_training|archive|arts_centre|bicycle_rental|biergarten|boat_rental|boat_storage|bureau_de_change|canteen|car_rental|car_wash|casino|childcare|clinic|college|conference_centre|courthouse|coworking_space|crematorium|dancing_school|dentist|dive_centre|doctors)$"](area.searchArea);
nw["amenity"~"^(cafe|bar|restaurant|library|cinema|fast_food|post_office|marketplace|community_centre|theatre|bank|townhall|animal_boarding|animal_breeding|animal_shelter|animal_training|archive|arts_centre|bicycle_rental|biergarten|boat_rental|boat_storage|bureau_de_change|canteen|car_rental|car_wash|casino|childcare|clinic|college|conference_centre|courthouse|coworking_space|crematorium|dancing_school|dentist|dive_centre|doctors|vehicle_inspection|driving_school)$"](area.searchArea);
nw["shop"]["shop"!~"vacant"](area.searchArea);
nw["tourism"~"^(hotel|hostel|motel|wilderness_hut|yes|chalet|gallery|guest_house|museum|zoo|theme_park|aquarium|alpine_hut|apartment)$"](area.searchArea);
nw["healthcare"](area.searchArea);
@ -583,6 +583,15 @@ area["ref:INSEE"="$zone"]->.searchArea;
nwr["amenity"="school"](area.searchArea);
nwr["amenity"="police"](area.searchArea);
nwr["amenity"="bicycle_parking"](area.searchArea);
nwr["advertising"="board"]["message"="political"](area.searchArea);
way["building"](area.searchArea);
nwr["email"](area.searchArea);
nwr["contact:email"](area.searchArea);
nwr["amenity"="bench"](area.searchArea);
nwr["amenity"="waste_basket"](area.searchArea);
nwr["highway"="street_lamp"](area.searchArea);
nwr["amenity"="drinking_water"](area.searchArea);
nwr["natural"="tree"](area.searchArea);
);
(._;>;);
out meta;

View file

@ -0,0 +1,98 @@
{% extends 'base_embed.html.twig' %}
{% block title %}Graphe thématique : {{ label }}{% endblock %}
{% block body %}
<div class="container mt-4">
<h1><i class="bi {{ icon }} fs-2"></i> {{ label }}</h1>
<canvas id="embedThemeChart" width="600" height="300"></canvas>
<div class="mb-3 mt-2">
<a href="{{ path('app_admin_stats', {'insee_code': stats.zone}) }}" class="btn btn-info me-2">
<i class="bi bi-bar-chart"></i> Voir la page de la ville
</a>
<a href="https://osm-mon-commerce.fr/?insee={{ stats.zone }}" target="_blank" class="btn btn-success me-2">
<i class="bi bi-globe"></i> OSM Mon Commerce
</a>
</div>
</div>
{% endblock %}
{% block javascripts %}
{{ parent() }}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns@3.0.0"></script>
<script>
const series = {{ series|json_encode|raw }};
const theme = {{ theme|json_encode|raw }};
const label = {{ label|json_encode|raw }};
const countData = (series[theme + '_count'] || []).map(e => ({x: e.date, y: e.value}));
const completionData = (series[theme + '_completion'] || []).map(e => ({x: e.date, y: e.value}));
const canvas = document.getElementById('embedThemeChart');
if (canvas) {
new Chart(canvas, {
type: 'line',
data: {
datasets: [
{
label: 'Nombre',
data: countData,
borderColor: 'blue',
backgroundColor: 'rgba(0,0,255,0.1)',
fill: false,
yAxisID: 'y',
},
{
label: 'Complétion (%)',
data: completionData,
borderColor: 'green',
backgroundColor: 'rgba(0,255,0,0.1)',
fill: false,
yAxisID: 'y1',
}
]
},
options: {
parsing: true,
responsive: true,
plugins: {
title: {
display: true,
text: label
}
},
scales: {
x: { type: 'time', time: { unit: 'day' }, title: { display: true, text: 'Date' } },
y: { beginAtZero: true, title: { display: true, text: 'Nombre' } },
y1: { beginAtZero: true, position: 'right', title: { display: true, text: 'Complétion (%)' }, grid: { drawOnChartArea: false } }
}
}
});
}
// Affichage de la progression sur une semaine
function getDelta(data, days) {
if (!data.length) return null;
const now = new Date(data[data.length - 1].x);
const refDate = new Date(now.getTime() - days * 24 * 60 * 60 * 1000);
let ref = null;
for (let i = data.length - 1; i >= 0; i--) {
const d = new Date(data[i].x);
if (d <= refDate) {
ref = data[i].y;
break;
}
}
const last = data[data.length - 1].y;
return ref !== null ? last - ref : null;
}
function formatDelta(val) {
if (val === null) return '-';
if (val === 0) return '0';
return (val > 0 ? '+' : '') + val;
}
const delta7dCount = formatDelta(getDelta(countData, 7));
const infoDiv = document.createElement('div');
infoDiv.className = 'mt-3 alert alert-info';
infoDiv.innerHTML = `<strong>Progression sur 7 jours :</strong> ${delta7dCount}`;
canvas.parentNode.appendChild(infoDiv);
</script>
{% endblock %}

View file

@ -28,6 +28,9 @@
<a href="http://127.0.0.1:8111/import?url=https://overpass-api.de/api/interpreter?data={{ overpass_query|url_encode }}" target="_blank" class="btn btn-sm btn-outline-success">
<i class="bi bi-box-arrow-in-up-right"></i> Ouvrir dans JOSM
</a>
<a href="{{ path('admin_followup_embed_graph', {'insee_code': stats.zone, 'theme': type}) }}" target="_blank" class="btn btn-sm btn-outline-secondary ms-2">
<i class="bi bi-code-slash"></i> Version embarquée
</a>
</div>
{% endfor %}
<h2 class="mt-4">Données brutes</h2>

View file

@ -0,0 +1,51 @@
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}Welcome!{% endblock %}</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 128 128%22><text y=%221.2em%22 font-size=%2296%22>⚫️</text></svg>">
<link rel="icon" type="image/png" href="{{ asset('logo-osm.png') }}">
{# Run `composer require symfony/webpack-encore-bundle` to start using Symfony UX #}
{% block stylesheets %}
{{ encore_entry_link_tags('app') }}
<link href='{{ asset('js/mapbox/mapbox-gl.css') }}' rel='stylesheet' />
<!-- CSS Bootstrap -->
<link rel="stylesheet" href="{{ asset('css/bootstrap-icons.css') }}">
<link rel="stylesheet" href="{{ asset('js/bootstrap/bootstrap-icons.min.css') }}">
<link href="{{ asset('js/bootstrap/bootstrap.min.css') }}" rel="stylesheet">
<!-- CSS personnalisé -->
<link rel="stylesheet" href="{{ asset('css/main.css') }}">
{% endblock %}
</head>
<body>
{% for label, messages in app.flashes %}
{% for message in messages %}
<div class="alert alert-{{ label }} is-{{ label }} alert-dismissible fade show mt-3" role="alert">
{{ message }}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}
{% endfor %}
<main class="body-landing">
{% block body %}{% endblock %}
</main>
<footer class="main-footer">
{% include 'public/nav.html.twig' %}
</footer>
{% block javascripts %}
{{ encore_entry_script_tags('app') }}
<script src="{{ asset('js/bootstrap/bootstrap.bundle.min.js') }}"></script>
<script src='{{ asset('js/maplibre/maplibre-gl.js') }}'></script>
{% endblock %}
{% block completion_progress %}
{% endblock %}
</body>
</html>