carte des villes et ajout de ville sur accueil

This commit is contained in:
Tykayn 2025-07-05 12:55:33 +02:00 committed by tykayn
parent 56f62c45bb
commit a2936841f9
8 changed files with 601 additions and 30 deletions

View file

@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20250705104136 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql(<<<'SQL'
ALTER TABLE place CHANGE email email VARCHAR(255) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_0900_ai_ci`, CHANGE note note VARCHAR(255) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_0900_ai_ci`, CHANGE name name VARCHAR(255) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_0900_ai_ci`, CHANGE note_content note_content VARCHAR(255) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_0900_ai_ci`, CHANGE street street VARCHAR(255) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_0900_ai_ci`, CHANGE housenumber housenumber VARCHAR(255) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_0900_ai_ci`, CHANGE siret siret VARCHAR(255) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_0900_ai_ci`, CHANGE osm_user osm_user VARCHAR(255) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_0900_ai_ci`, CHANGE email_content email_content LONGTEXT CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_0900_ai_ci`
SQL);
$this->addSql(<<<'SQL'
ALTER TABLE stats ADD lat NUMERIC(10, 7) DEFAULT NULL, ADD lon NUMERIC(10, 7) DEFAULT NULL
SQL);
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql(<<<'SQL'
ALTER TABLE stats DROP lat, DROP lon
SQL);
$this->addSql(<<<'SQL'
ALTER TABLE place CHANGE email email VARCHAR(255) DEFAULT NULL, CHANGE note note VARCHAR(255) DEFAULT NULL, CHANGE name name VARCHAR(255) DEFAULT NULL, CHANGE note_content note_content VARCHAR(255) DEFAULT NULL, CHANGE street street VARCHAR(255) DEFAULT NULL, CHANGE housenumber housenumber VARCHAR(255) DEFAULT NULL, CHANGE siret siret VARCHAR(255) DEFAULT NULL, CHANGE osm_user osm_user VARCHAR(255) DEFAULT NULL, CHANGE email_content email_content LONGTEXT DEFAULT NULL
SQL);
}
}

View file

@ -0,0 +1,210 @@
<?php
namespace App\Command;
use App\Entity\Stats;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'app:update-city-coordinates',
description: 'Met à jour les coordonnées de toutes les villes via l\'API Nominatim',
)]
class UpdateCityCoordinatesCommand extends Command
{
public function __construct(
private EntityManagerInterface $entityManager
) {
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$stats = $this->entityManager->getRepository(Stats::class)->findAll();
$total = count($stats);
$updated = 0;
$errors = 0;
$io->progressStart($total);
foreach ($stats as $stat) {
if ($stat->getZone() && $stat->getZone() !== 'undefined' && preg_match('/^\d+$/', $stat->getZone())) {
$cityName = $stat->getName() ?: $stat->getZone();
// Vérifier si les coordonnées sont déjà présentes
if (!$stat->getLat() || !$stat->getLon()) {
$coordinates = $this->getCityCoordinates($cityName, $stat->getZone());
if ($coordinates) {
$stat->setLat((string) $coordinates['lat']);
$stat->setLon((string) $coordinates['lon']);
$this->entityManager->persist($stat);
$updated++;
$io->text("$cityName ({$stat->getZone()}): " . $coordinates['lat'] . ", " . $coordinates['lon']);
} else {
$errors++;
$io->warning("✗ Impossible de récupérer les coordonnées pour $cityName ({$stat->getZone()})");
}
}
}
$io->progressAdvance();
}
$this->entityManager->flush();
$io->progressFinish();
$io->success("Mise à jour terminée : $updated villes mises à jour, $errors erreurs");
return Command::SUCCESS;
}
private function getCityCoordinates(string $cityName, string $inseeCode): ?array
{
// Stratégie 1: Nominatim
$coordinates = $this->getCoordinatesFromNominatim($cityName);
if ($coordinates) {
return $coordinates;
}
// Stratégie 2: Premier objet Place townhall
$coordinates = $this->getCoordinatesFromPlaceTownhall($inseeCode);
if ($coordinates) {
return $coordinates;
}
// Stratégie 3: N'importe quel objet Place
$coordinates = $this->getCoordinatesFromAnyPlace($inseeCode);
if ($coordinates) {
return $coordinates;
}
// Stratégie 4: Addok
return $this->getCoordinatesFromAddok($cityName, $inseeCode);
}
private function getCoordinatesFromNominatim(string $cityName): ?array
{
$query = urlencode($cityName . ', France');
$url = "https://nominatim.openstreetmap.org/search?q={$query}&format=json&limit=1&countrycodes=fr";
try {
usleep(100000); // 0.1 seconde entre les appels
$context = stream_context_create([
'http' => [
'timeout' => 5,
'user_agent' => 'OSM-Commerces/1.0'
]
]);
$response = file_get_contents($url, false, $context);
if ($response === false) {
return null;
}
$data = json_decode($response, true);
if (!empty($data) && isset($data[0]['lat']) && isset($data[0]['lon'])) {
return [
'lat' => (float) $data[0]['lat'],
'lon' => (float) $data[0]['lon']
];
}
} catch (\Exception $e) {
// En cas d'erreur, on retourne null
}
return null;
}
private function getCoordinatesFromPlaceTownhall(string $inseeCode): ?array
{
$places = $this->entityManager->getRepository(\App\Entity\Place::class)
->createQueryBuilder('p')
->where('p.zip_code = :inseeCode')
->andWhere('p.lat IS NOT NULL')
->andWhere('p.lon IS NOT NULL')
->andWhere('p.main_tag = :mainTag')
->setParameter('inseeCode', $inseeCode)
->setParameter('mainTag', 'townhall')
->setMaxResults(1)
->getQuery()
->getResult();
if (!empty($places)) {
$place = $places[0];
return [
'lat' => (float) $place->getLat(),
'lon' => (float) $place->getLon()
];
}
return null;
}
private function getCoordinatesFromAnyPlace(string $inseeCode): ?array
{
$places = $this->entityManager->getRepository(\App\Entity\Place::class)
->createQueryBuilder('p')
->where('p.zip_code = :inseeCode')
->andWhere('p.lat IS NOT NULL')
->andWhere('p.lon IS NOT NULL')
->setParameter('inseeCode', $inseeCode)
->setMaxResults(1)
->getQuery()
->getResult();
if (!empty($places)) {
$place = $places[0];
return [
'lat' => (float) $place->getLat(),
'lon' => (float) $place->getLon()
];
}
return null;
}
private function getCoordinatesFromAddok(string $cityName, string $inseeCode): ?array
{
$query = urlencode($cityName . ', France');
$url = "https://demo.addok.xyz/search?q={$query}&limit=1";
try {
$context = stream_context_create([
'http' => [
'timeout' => 5,
'user_agent' => 'OSM-Commerces/1.0'
]
]);
$response = file_get_contents($url, false, $context);
if ($response === false) {
return null;
}
$data = json_decode($response, true);
if (!empty($data['features']) && isset($data['features'][0]['geometry']['coordinates'])) {
$coordinates = $data['features'][0]['geometry']['coordinates'];
return [
'lat' => (float) $coordinates[1], // Addok retourne [lon, lat]
'lon' => (float) $coordinates[0]
];
}
} catch (\Exception $e) {
// En cas d'erreur, on retourne null
}
return null;
}
}

View file

@ -122,17 +122,20 @@ class PublicController extends AbstractController
// Préparer les données pour la carte
$citiesForMap = [];
foreach ($stats as $stat) {
if ($stat->getZone() && $stat->getZone() !== 'undefined' && preg_match('/^\d+$/', $stat->getZone())) {
// Récupérer les coordonnées de la ville via l'API Nominatim
if ($stat->getZone() && $stat->getZone() !== 'undefined' && preg_match('/^\d+$/', $stat->getZone()) && $stat->getZone() !== '00000') {
$cityName = $stat->getName() ?: $stat->getZone();
$coordinates = $this->getCityCoordinates($cityName, $stat->getZone());
if ($coordinates) {
// Utiliser les coordonnées stockées si disponibles
if ($stat->getLat() && $stat->getLon()) {
$citiesForMap[] = [
'name' => $cityName,
'zone' => $stat->getZone(),
'coordinates' => $coordinates,
'coordinates' => [
'lat' => (float) $stat->getLat(),
'lon' => (float) $stat->getLon()
],
'placesCount' => $stat->getPlacesCount(),
'completionPercent' => $stat->getCompletionPercent(),
'population' => $stat->getPopulation(),
@ -165,17 +168,36 @@ class PublicController extends AbstractController
$url = "https://nominatim.openstreetmap.org/search?q={$query}&format=json&limit=1&countrycodes=fr";
try {
$response = file_get_contents($url);
// Ajouter un délai pour respecter les limites de l'API Nominatim
usleep(100000); // 0.1 seconde entre les appels
$context = stream_context_create([
'http' => [
'timeout' => 5, // Timeout de 5 secondes
'user_agent' => 'OSM-Commerces/1.0'
]
]);
$response = file_get_contents($url, false, $context);
if ($response === false) {
error_log("DEBUG: Échec de récupération des coordonnées pour $cityName ($inseeCode)");
return null;
}
$data = json_decode($response, true);
if (!empty($data) && isset($data[0]['lat']) && isset($data[0]['lon'])) {
error_log("DEBUG: Coordonnées trouvées pour $cityName ($inseeCode): " . $data[0]['lat'] . ", " . $data[0]['lon']);
return [
'lat' => (float) $data[0]['lat'],
'lon' => (float) $data[0]['lon']
];
} else {
error_log("DEBUG: Aucune coordonnée trouvée pour $cityName ($inseeCode)");
}
} catch (\Exception $e) {
// En cas d'erreur, on retourne null
error_log("DEBUG: Exception lors de la récupération des coordonnées pour $cityName ($inseeCode): " . $e->getMessage());
}
return null;
@ -601,4 +623,61 @@ class PublicController extends AbstractController
'logs' => $logs
]);
}
#[Route('/add-city', name: 'app_public_add_city')]
public function addCity(): Response
{
return $this->render('public/add_city.html.twig', [
'controller_name' => 'PublicController',
]);
}
#[Route('/stats/{insee_code}/followup-graph/{theme}', name: 'app_public_followup_graph', requirements: ['insee_code' => '\\d+', 'theme' => '[a-zA-Z0-9_]+'])]
public function publicFollowupGraph(string $insee_code, string $theme): Response
{
$stats = $this->entityManager->getRepository(Stats::class)->findOneBy(['zone' => $insee_code]);
if (!$stats) {
$this->addFlash('error', 'Aucune stats trouvée pour ce code INSEE.');
return $this->redirectToRoute('app_public_index');
}
$themes = \App\Service\FollowUpService::getFollowUpThemes();
if (!isset($themes[$theme])) {
$this->addFlash('error', 'Thème non reconnu.');
return $this->redirectToRoute('app_public_index');
}
// Récupérer toutes les données de followup pour ce thème
$followups = $stats->getCityFollowUps();
$countData = [];
$completionData = [];
foreach ($followups as $fu) {
if ($fu->getName() === $theme . '_count') {
$countData[] = [
'date' => $fu->getDate()->format('Y-m-d'),
'value' => $fu->getMeasure()
];
}
if ($fu->getName() === $theme . '_completion') {
$completionData[] = [
'date' => $fu->getDate()->format('Y-m-d'),
'value' => $fu->getMeasure()
];
}
}
// Trier par date
usort($countData, fn($a, $b) => $a['date'] <=> $b['date']);
usort($completionData, fn($a, $b) => $a['date'] <=> $b['date']);
return $this->render('public/followup_graph.html.twig', [
'stats' => $stats,
'theme' => $theme,
'theme_label' => $themes[$theme],
'count_data' => json_encode($countData),
'completion_data' => json_encode($completionData),
'icons' => \App\Service\FollowUpService::getFollowUpIcons(),
]);
}
}

View file

@ -98,6 +98,12 @@ class Stats
#[ORM\Column(type: Types::DECIMAL, precision: 15, scale: 2, nullable: true)]
private ?string $budget_annuel = null;
#[ORM\Column(type: Types::DECIMAL, precision: 10, scale: 7, nullable: true)]
private ?string $lat = null;
#[ORM\Column(type: Types::DECIMAL, precision: 10, scale: 7, nullable: true)]
private ?string $lon = null;
/**
* @var Collection<int, CityFollowUp>
*/
@ -599,6 +605,28 @@ class Stats
}
return $this;
}
public function getLat(): ?string
{
return $this->lat;
}
public function setLat(?string $lat): static
{
$this->lat = $lat;
return $this;
}
public function getLon(): ?string
{
return $this->lon;
}
public function setLon(?string $lon): static
{
$this->lon = $lon;
return $this;
}
}

View file

@ -484,9 +484,9 @@
['has', 'completion'],
[
'rgb',
['-', 255, ['*', ['get', 'completion'], 2.55]],
0,
['*', ['get', 'completion'], 2.55],
80
0
],
'#cccccc'
],

View file

@ -0,0 +1,28 @@
{% extends 'base.html.twig' %}
{% block title %}Ajouter ma ville{% endblock %}
{% block body %}
<div class="container mt-4">
<div class="row">
<div class="col-12">
<div class="d-flex justify-content-between align-items-center mb-4">
<h1><i class="bi bi-plus-circle"></i> Ajouter ma ville</h1>
<a href="{{ path('app_public_index') }}" class="btn btn-secondary">
<i class="bi bi-arrow-left"></i> Retour à l'accueil
</a>
</div>
<div class="card">
<div class="card-header">
<h3><i class="bi bi-geo-alt"></i> Labourage d'une nouvelle ville</h3>
<p class="mb-0">Entrez le code INSEE de votre ville pour l'ajouter à notre base de données</p>
</div>
<div class="card-body">
{% include 'public/labourage-form.html.twig' %}
</div>
</div>
</div>
</div>
</div>
{% endblock %}

View file

@ -0,0 +1,153 @@
{% extends 'base.html.twig' %}
{% block title %}Graphe thématique : {{ theme_label }} - {{ stats.name }}{% endblock %}
{% block stylesheets %}
{{ parent() }}
<link href='{{ asset('js/maplibre/maplibre-gl.css') }}' rel='stylesheet'/>
{% endblock %}
{% block body %}
<div class="container mt-4">
<div class="row">
<div class="col-12">
<div class="d-flex justify-content-between align-items-center mb-4">
<div>
<h1><i class="bi {{ icons[theme]|default('bi-question-circle') }}"></i> {{ theme_label }}</h1>
<p class="text-muted mb-0">{{ stats.name }} ({{ stats.zone }})</p>
</div>
<div>
<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="{{ path('app_public_index') }}" class="btn btn-secondary">
<i class="bi bi-arrow-left"></i> Retour à l'accueil
</a>
</div>
</div>
<div class="card">
<div class="card-header">
<h3><i class="bi bi-graph-up"></i> Évolution du {{ theme_label|lower }}</h3>
<p class="mb-0">Suivi de la progression du nombre d'objets et du taux de complétion</p>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-6">
<h5>Nombre d'objets</h5>
<canvas id="countChart" height="300"></canvas>
</div>
<div class="col-md-6">
<h5>Taux de complétion (%)</h5>
<canvas id="completionChart" height="300"></canvas>
</div>
</div>
<div class="mt-4">
<div class="alert alert-info">
<i class="bi bi-info-circle"></i>
<strong>Informations :</strong> Ces graphiques montrent l'évolution du {{ theme_label|lower }} dans {{ stats.name }} au fil du temps.
Le taux de complétion indique le pourcentage d'objets correctement renseignés.
</div>
</div>
</div>
</div>
</div>
</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>
document.addEventListener('DOMContentLoaded', function() {
const countData = {{ count_data|raw }};
const completionData = {{ completion_data|raw }};
// Graphique du nombre d'objets
const countCtx = document.getElementById('countChart').getContext('2d');
new Chart(countCtx, {
type: 'line',
data: {
labels: countData.map(d => d.date),
datasets: [{
label: 'Nombre d\'objets',
data: countData.map(d => d.value),
borderColor: 'rgb(54, 162, 235)',
backgroundColor: 'rgba(54, 162, 235, 0.1)',
tension: 0.3,
fill: false
}]
},
options: {
responsive: true,
plugins: {
title: {
display: true,
text: 'Évolution du nombre d\'objets'
}
},
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: 'Nombre d\'objets'
}
},
x: {
title: {
display: true,
text: 'Date'
}
}
}
}
});
// Graphique du taux de complétion
const completionCtx = document.getElementById('completionChart').getContext('2d');
new Chart(completionCtx, {
type: 'line',
data: {
labels: completionData.map(d => d.date),
datasets: [{
label: 'Taux de complétion (%)',
data: completionData.map(d => d.value),
borderColor: 'rgb(75, 192, 192)',
backgroundColor: 'rgba(75, 192, 192, 0.1)',
tension: 0.3,
fill: false
}]
},
options: {
responsive: true,
plugins: {
title: {
display: true,
text: 'Évolution du taux de complétion'
}
},
scales: {
y: {
beginAtZero: true,
max: 100,
title: {
display: true,
text: 'Taux de complétion (%)'
}
},
x: {
title: {
display: true,
text: 'Date'
}
}
}
}
});
});
</script>
{% endblock %}

View file

@ -130,14 +130,38 @@
<br>Nous vous enverrons un lien unique pour cela par email, et si vous en avez besoin, nous pouvons
vous aider.
</p>
<div class="row">
<div class="col-12">
<label class="label" for="researchShop">
<i class="bi bi-search bi-2x"></i> Rechercher un commerce, écrivez son nom et la ville
</label>
<input class="form-control" type="text" id="researchShop" placeholder="Mon commerce, Paris">
</div>
</div>
<div id="resultsList"></div>
<div id="proposeLink" class="d-none"></div>
<div id="proposeMail" class="d-none">
<input type="email" id="emailInput" class="form-control"
placeholder="mon_email_de_commerce@exemple.com">
<button type="submit" class="btn btn-primary p-4 d-block"><i class="bi bi-envelope"></i> Envoyer
</button>
</div>
<div id="emailForm"></div>
{% if citiesForMap is not empty %}
<div class="row mb-4">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3><i class="bi bi-geo-alt"></i> Carte des villes disponibles</h3>
<p class="mb-0">Cliquez sur un marqueur pour voir les statistiques de la ville</p>
<div class="card-header d-flex justify-content-between align-items-center">
<div>
<h3><i class="bi bi-geo-alt"></i> Carte des villes disponibles</h3>
<p class="mb-0">Cliquez sur un marqueur pour voir les statistiques de la ville</p>
</div>
<a href="{{ path('app_public_add_city') }}" class="btn btn-success">
<i class="bi bi-plus-circle"></i> Ajouter ma ville
</a>
</div>
<div class="card-body p-0">
<div class="map-container">
@ -163,24 +187,7 @@
</div>
{% endif %}
<div class="row">
<div class="col-12">
<label class="label" for="researchShop">
<i class="bi bi-search bi-2x"></i> Rechercher un commerce, écrivez son nom et la ville
</label>
<input class="form-control" type="text" id="researchShop" placeholder="Mon commerce, Paris">
</div>
</div>
<div id="resultsList"></div>
<div id="proposeLink" class="d-none"></div>
<div id="proposeMail" class="d-none">
<input type="email" id="emailInput" class="form-control"
placeholder="mon_email_de_commerce@exemple.com">
<button type="submit" class="btn btn-primary p-4 d-block"><i class="bi bi-envelope"></i> Envoyer
</button>
</div>
<div id="emailForm"></div>
</div>
@ -311,6 +318,31 @@
`)
)
.addTo(map);
// Ajouter le nom de la ville comme label
const label = new maplibregl.Marker({
element: (() => {
const el = document.createElement('div');
el.className = 'city-label';
el.style.cssText = `
background: rgba(255, 255, 255, 0.9);
border: 1px solid #ccc;
border-radius: 4px;
padding: 2px 6px;
font-size: 11px;
font-weight: bold;
color: #333;
white-space: nowrap;
pointer-events: none;
margin-top: -25px;
margin-left: 15px;
`;
el.textContent = properties.name;
return el;
})()
})
.setLngLat(feature.geometry.coordinates)
.addTo(map);
});
// Ajouter les contrôles de navigation