récupérer les objets avec email dans une zone par code postal

This commit is contained in:
Tykayn 2025-05-26 12:57:10 +02:00 committed by tykayn
parent f5ab0c8205
commit cb240dd169
8 changed files with 348 additions and 73 deletions

View file

@ -5,9 +5,22 @@ namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use App\Entity\Place;
use App\Service\Motocultrice;
use Doctrine\ORM\EntityManagerInterface;
use function uuid_create;
final class AdminController extends AbstractController
{
public function __construct(
private EntityManagerInterface $entityManager,
private Motocultrice $motocultrice
) {
}
#[Route('/admin', name: 'app_admin')]
public function index(): Response
{
@ -15,4 +28,56 @@ final class AdminController extends AbstractController
'controller_name' => 'AdminController',
]);
}
#[Route('/admin/labourer/{zip_code}', name: 'app_admin_labourer')]
public function labourer_zone(string $zip_code): Response
{
$results = [];
// $zone = 'Briis sous forges';
$results = $this->motocultrice->labourer($zip_code);
// Récupérer les commerces existants dans la base de données pour cette zone
$commerces = $this->entityManager->getRepository(Place::class)->findBy(['zip_code' => $zip_code]);
$osm_object_ids = [];
if ($commerces) {
// Extraire les osm_object_ids des commerces existants
$osm_object_ids = array_map(function($commerce) {
return $commerce->getOsmId();
}, $commerces);
}
// pour chaque résultat, vérifier que l'on a pas déjà un commerce avec le même osm_object_id
$results = array_filter($results, function($commerce) use ($osm_object_ids) {
return !in_array($commerce['id'], $osm_object_ids);
});
// on crée un commerce pour chaque résultat qui reste
foreach ($results as $result) {
$commerce = new Place();
$commerce->setOsmId($result['id'])
->setOsmKind($result['type'])
->setName($result['name'])
->setZipCode($zip_code)
->setEmail($result['email'])
->setUuidForUrl($this->motocultrice->uuid_create())
->setOptedOut(false)
->setDead(false)
->setNote($result['note'] ?? null)
->setModifiedDate(new \DateTime())
->setAskedHumainsSupport(false)
->setLastContactAttemptDate(null)
->setStats(null);
$this->entityManager->persist($commerce);
}
$this->entityManager->flush();
return $this->render('admin/labourage_results.html.twig', [
'results' => $results,
'zone' => $zip_code,
]);
}
}

View file

@ -37,6 +37,20 @@ class PublicController extends AbstractController
]);
}
#[Route('/edit/{zipcode}/{name}/{uuid}', name: 'app_public_edit')]
public function edit_with_uuid($zipcode, $name, $uuid): Response
{
$place = $this->entityManager->getRepository(Place::class)->findOneBy(['uuid_for_url' => $uuid]);
if (!$place) {
return $this->redirectToRoute('app_public_index');
}
$commerce = $this->motocultrice->get_osm_object_data($place->getOsmKind(), $place->getOsmId());
return $this->render('public/edit.html.twig', [
'commerce' => $commerce,
'name' => $name,
]);
}
#[Route('/dashboard', name: 'app_public_dashboard')]
public function dashboard(): Response
{

View file

@ -3,28 +3,48 @@
namespace App\Service;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Doctrine\ORM\EntityManagerInterface;
class Motocultrice
{
private $overpassApiUrl = 'https://overpass-api.de/api/interpreter';
public function __construct(
private HttpClientInterface $client
private HttpClientInterface $client,
private EntityManagerInterface $entityManager
) {
}
public function labourer(string $zone): array
{
if (!$zone) {
throw new \InvalidArgumentException("La zone ne peut pas être vide");
}
// Nettoyer et échapper la zone pour la requête
$zone = addslashes(trim($zone));
$query = <<<QUERY
[out:json][timeout:25];
area["name"="{$zone}"]->.searchArea;
area["postal_code"="{$zone}"]->.searchArea;
(
nwr["shop"](area.searchArea);
// Recherche des commerces et services avec email
nw["amenity"]["contact:email"](area.searchArea);
nw["amenity"]["email"](area.searchArea);
nw["shop"]["contact:email"](area.searchArea);
nw["shop"]["email"](area.searchArea);
nw["office"]["contact:email"](area.searchArea);
nw["office"]["email"](area.searchArea);
// Recherche des commerces et services sans email pour référence
nw["amenity"](area.searchArea);
nw["shop"](area.searchArea);
nw["office"](area.searchArea);
);
out body;
>;
out skel qt;
QUERY;
QUERY;
try {
$response = $this->client->request('POST', $this->overpassApiUrl, [
@ -33,15 +53,21 @@ class Motocultrice
$data = json_decode($response->getContent(), true);
$shops = [];
$places = [];
if (isset($data['elements'])) {
foreach ($data['elements'] as $element) {
if (isset($element['tags']['shop'])) {
$shops[] = [
if (isset($element['tags'])) {
$email = $element['tags']['contact:email'] ?? $element['tags']['email'] ?? null;
// On passe si pas d'email
if (!$email) {
continue;
}
$places[] = [
'id' => $element['id'],
'type' => $element['type'],
'name' => $element['tags']['name'] ?? 'Sans nom',
'shop_type' => $element['tags']['shop'],
'name' => $element['tags']['name'] ?? '',
'email' => $email,
'lat' => $element['lat'] ?? null,
'lon' => $element['lon'] ?? null,
'tags' => $element['tags']
@ -50,15 +76,15 @@ class Motocultrice
}
}
return $shops;
return $places;
} catch (\Exception $e) {
throw new \Exception("Erreur lors de la requête Overpass : " . $e->getMessage());
}
}
public function get_osm_object_data($osm_object_id = 12855459190)
public function get_osm_object_data($osm_kind = 'node', $osm_object_id = 12855459190)
{
$object_id = "https://www.openstreetmap.org/api/0.6/node/".$osm_object_id;
$object_id = "https://www.openstreetmap.org/api/0.6/".$osm_kind."/".$osm_object_id;
try {
$response = $this->client->request('GET', $object_id);
@ -71,21 +97,48 @@ class Motocultrice
// convertir les tags en clés et valeurs
$osm_object_data['tags_converted'] = [];
// Initialiser le tableau des tags convertis
if (isset($osm_object_data['node'])) {
$osm_object_data['node']['tags_converted'] = [];
} elseif (isset($osm_object_data['way'])) {
$osm_object_data['way']['tags_converted'] = [];
}
if(isset($osm_object_data['node'])){
foreach ($osm_object_data['node']['tag'] as $attribute) {
$osm_object_data['node']['tags_converted'][$attribute['@attributes']['k']] = $attribute['@attributes']['v'];
}
return $osm_object_data['node'];
}
public function semer(): string
{
return "La motocultrice sème les graines";
if(isset($osm_object_data['way'])){
foreach ($osm_object_data['way']['tag'] as $attribute) {
$osm_object_data['way']['tags_converted'][$attribute['@attributes']['k']] = $attribute['@attributes']['v'];
}
return $osm_object_data['way'];
}
public function récolter(): string
{
return "La motocultrice récolte les cultures";
return $osm_object_data;
}
public function uuid_create() {
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
// 32 bits for "time_low"
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
// 16 bits for "time_mid"
mt_rand( 0, 0xffff ),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand( 0, 0x0fff ) | 0x4000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand( 0, 0x3fff ) | 0x8000,
// 48 bits for "node"
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
);
}
}

View file

@ -11,10 +11,5 @@
<div class="example-wrapper">
<h1>Hello {{ controller_name }}! ✅</h1>
This friendly message is coming from:
<ul>
<li>Your controller at <code>/home/poule/encrypted/stockage-syncable/www/development/html/osm-commerce-sf/src/Controller/AdminController.php</code></li>
<li>Your template at <code>/home/poule/encrypted/stockage-syncable/www/development/html/osm-commerce-sf/templates/admin/index.html.twig</code></li>
</ul>
</div>
{% endblock %}

View file

@ -0,0 +1,25 @@
{% extends 'base.html.twig' %}
{% block title %}Hello AdminController!{% endblock %}
{% block body %}
<style>
.example-wrapper { margin: 1em auto; max-width: 800px; width: 95%; font: 18px/1.5 sans-serif; }
.example-wrapper code { background: #F5F5F5; padding: 2px 6px; }
</style>
<div class="example-wrapper">
<h1>Labourage fait sur la zone "{{ zone }}" ✅</h1>
{# {{ dump(results) }} #}
{% for commerce in results %}
<p>
{{ commerce.name }}
</p>
<pre>
{{ dump(commerce) }}
</pre>
{% endfor %}
</div>
{% endblock %}

View file

@ -49,6 +49,8 @@
<th>Date de modification</th>
<th>Date de dernier contact</th>
<th>Date de dernière modification</th>
<th>Code postal</th>
</tr>
@ -61,7 +63,17 @@
<td>{{ place.modifiedDate | date('Y-m-d H:i:s') }}</td>
<td>{{ place.lastContactAttemptDate | date('Y-m-d H:i:s') }}</td>
<td>{{ place.modifiedDate | date('Y-m-d H:i:s') }}</td>
<td>{{ place.zipCode }}</td>
<td>
<a href="https://www.openstreetmap.org/{{place.osmKind}}/{{ place.osmId }}" target="_blank">Voir dans OSM</a>
{% if place.name %}
<a href="{{ path('app_public_edit', {'zipcode': place.zipCode, 'name': place.name, 'uuid': place.uuidForUrl}) }}">Modifier</a>
{% else %}
<a href="{{ path('app_public_edit', {'zipcode': place.zipCode, 'name': '?', 'uuid': place.uuidForUrl}) }}">Modifier</a>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>

View file

@ -0,0 +1,151 @@
{% extends 'base.html.twig' %}
{% block title %}{{ 'display.title'|trans }}{% endblock %}
{% block stylesheets %}
{{ parent() }}
<link href='https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.css' rel='stylesheet' />
<style>
.hidden {
display: none;
}
</style>
{% endblock %}
{% block body %}
<div class="container mt-4">
<div class="row">
<div class="col-12">
<nav class="navbar navbar-expand-lg navbar-light bg-light mb-4 rounded shadow-sm">
<div class="container-fluid">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active" href="{{ path('app_public_index') }}">{{ 'display.home'|trans }}</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ path('app_public_dashboard') }}">{{ 'display.stats'|trans }}</a>
</li>
<li class="nav-item">
<a class="nav-link" href="https://openstreetmap.fr/contact/">{{ 'display.contact_humans'|trans }}</a>
</li>
</ul>
</div>
</div>
</nav>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="card shadow-sm">
<div class="card-body">
<h1 class="card-title mb-4">{{ 'display.welcome'|trans }}</h1>
<div id="map" style="height: 400px; width: 100%;" class="rounded"></div>
{% if commerce is not empty %}
<div class="row mb-4">
<div class="col-12">
</div>
</div>
<form action="{{ path('app_public_submit', {'osm_object_id': commerce['@attributes'].id, 'version': commerce['@attributes'].version, 'changesetID': commerce['@attributes'].changeset }) }}" method="post" class="needs-validation">
<div class="mb-3">
<label for="commerce_id" class="form-label">{{ 'display.modify_commerce'|trans }}:
<strong>{{ commerce.tags_converted.name }}</strong>
</label>
<br/>
<a class="btn btn-info" href="{{ path('app_public_index') }}">{{ 'display.contact_humans'|trans }}</a>
</div>
<h2>{{ 'display.tags'|trans }}</h2>
<fieldset>
{% for attributes in commerce.tag %}
{% for kv in attributes %}
{% if kv.k == 'opening_hours' %}
{{ 'display.keys.opening_hours'|trans }}
{% else %}
<div class="row mb-3">
<div class="col-md-5">
<input type="text" class="form-control hidden" name="commerce_tag_key__{{ kv.k }}" value="{{ kv.k }}" readonly>
<span class="label-translated">{{ ('display.keys.' ~ kv.k)|trans }}</span>
</div>
<div class="col-md-5">
<input type="text" class="form-control" name="commerce_tag_value__{{ kv.k }}" value="{{ kv.v }}">
</div>
</div>
{% endif %}
{% endfor %}
{% endfor %}
</fieldset>
<button type="submit" class="btn btn-primary">{{ 'display.submit'|trans }}</button>
</form>
{% endif %}
</div>
</div>
</div>
<span class="p-3">
<span class="last-modification">{{ 'display.last_modification'|trans }}: {{ commerce['@attributes'].timestamp }}</span>,
{{ 'display.days_ago'|trans({'%days%': date(commerce['@attributes'].timestamp).diff(date()).days}) }}
{{ 'display.by'|trans }}
<a href="https://www.openstreetmap.org/user/{{ commerce['@attributes'].user }}" target="_blank">{{ commerce['@attributes'].user }}</a>
<div class="lien-OpenStreetMap">
<a href="https://www.openstreetmap.org/node/{{ commerce['@attributes'].id }}" target="_blank">{{ 'display.view_on_osm'|trans }}</a>
</div>
</span>
<div class="disclaimer p-3">
<p>
<strong>{{ 'display.disclaimer.title'|trans }}:</strong>
{{ 'display.disclaimer.text'|trans }}
</p>
</div>
</div>
<div class="row mt-4">
<div class="col-12">
<nav class="bg-light p-3 rounded shadow-sm">
<ul class="nav justify-content-center">
<li class="nav-item">
<a class="nav-link" href="{{ path('app_public_index') }}">{{ 'display.home'|trans }}</a>
</li>
<li class="nav-item">
<a class="nav-link" href="https://openstreetmap.fr/contact/">{{ 'display.contact_humans'|trans }}</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
{% block javascripts %}
{{ parent() }}
{# <script src='https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.js'></script> #}
{# <script>
{% if commerce is not empty %}
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['@attributes'].lon }}, {{ commerce['@attributes'].lat }}],
zoom: 14
});
// Ajout du marqueur
new mapboxgl.Marker()
.setLngLat([{{ commerce.lon }}, {{ commerce.lat }}])
.setPopup(new mapboxgl.Popup({
offset: 25
}).setHTML('<h1>{{ commerce.tags_converted.name }}</h1>'))
.addTo(map);
{% endif %}
</script> #}
{% endblock %}
{% endblock %}

View file

@ -46,49 +46,9 @@
<h1 class="card-title mb-4">{{ 'display.welcome'|trans }}</h1>
<div id="map" style="height: 400px; width: 100%;" class="rounded"></div>
{% if commerce is not empty %}
<div class="row mb-4">
<div class="col-12">
</div>
</div>
<form action="{{ path('app_public_submit', {'osm_object_id': commerce['@attributes'].id, 'version': commerce['@attributes'].version, 'changesetID': commerce['@attributes'].changeset }) }}" method="post" class="needs-validation">
<div class="mb-3">
<label for="commerce_id" class="form-label">{{ 'display.modify_commerce'|trans }}:
<strong>{{ commerce.tags_converted.name }}</strong>
</label>
<br/>
<a class="btn btn-info" href="{{ path('app_public_index') }}">{{ 'display.contact_humans'|trans }}</a>
</div>
<h2>{{ 'display.tags'|trans }}</h2>
<fieldset>
{% for attributes in commerce.tag %}
{% for kv in attributes %}
{% if kv.k == 'opening_hours' %}
{{ 'display.keys.opening_hours'|trans }}
{% else %}
<div class="row mb-3">
<div class="col-md-5">
<input type="text" class="form-control hidden" name="commerce_tag_key__{{ kv.k }}" value="{{ kv.k }}" readonly>
<span class="label-translated">{{ ('display.keys.' ~ kv.k)|trans }}</span>
</div>
<div class="col-md-5">
<input type="text" class="form-control" name="commerce_tag_value__{{ kv.k }}" value="{{ kv.v }}">
</div>
</div>
{% endif %}
{% endfor %}
{% endfor %}
</fieldset>
<button type="submit" class="btn btn-primary">{{ 'display.submit'|trans }}</button>
</form>
{% endif %}
</div>
</div>
</div>
<span class="p-3">
<span class="last-modification">{{ 'display.last_modification'|trans }}: {{ commerce['@attributes'].timestamp }}</span>,