up recherche home

This commit is contained in:
Tykayn 2025-07-18 17:08:13 +02:00 committed by tykayn
parent c89751b45c
commit 7887356dd9
3 changed files with 281 additions and 251 deletions

View file

@ -2,23 +2,22 @@
namespace App\Controller; namespace App\Controller;
use App\Entity\Stats;
use App\Entity\Place;
use App\Entity\CityFollowUp; use App\Entity\CityFollowUp;
use App\Entity\Demande; use App\Entity\Demande;
use App\Service\Motocultrice; use App\Entity\Place;
use App\Service\FollowUpService; use App\Entity\Stats;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use GuzzleHttp\Client;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mailer\MailerInterface;
use App\Service\ActionLogger; use App\Service\ActionLogger;
use Symfony\Component\HttpFoundation\ResponseHeaderBag; use App\Service\FollowUpService;
use App\Service\Motocultrice;
use Doctrine\ORM\EntityManagerInterface;
use GuzzleHttp\Client;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Routing\Annotation\Route;
class PublicController extends AbstractController class PublicController extends AbstractController
{ {
@ -27,11 +26,13 @@ class PublicController extends AbstractController
public function __construct( public function __construct(
private EntityManagerInterface $entityManager, private EntityManagerInterface $entityManager,
private Motocultrice $motocultrice, private Motocultrice $motocultrice,
private MailerInterface $mailer, private MailerInterface $mailer,
private ActionLogger $actionLogger, private ActionLogger $actionLogger,
private FollowUpService $followUpService private FollowUpService $followUpService
) {} )
{
}
#[Route('/propose-email/{email}/{type}/{id}', name: 'app_public_propose_email')] #[Route('/propose-email/{email}/{type}/{id}', name: 'app_public_propose_email')]
public function proposeEmail(string $email, string $type, int $id): Response public function proposeEmail(string $email, string $type, int $id): Response
@ -60,11 +61,11 @@ class PublicController extends AbstractController
$debug = ''; $debug = '';
if ($this->getParameter('kernel.environment') !== 'prod') { if ($this->getParameter('kernel.environment') !== 'prod') {
$debug = 'Bonjour, nous sommes des bénévoles d\'OpenStreetMap France et nous vous proposons de modifier les informations de votre commerce. Voici votre lien unique de modification: ' . $this->generateUrl('app_public_edit', [ $debug = 'Voici votre lien unique de modification: <a href="' . $this->generateUrl('app_public_edit', [
'zipcode' => $zipCode, 'zipcode' => $zipCode,
'name' => $place_name, 'name' => $place_name,
'uuid' => $existingPlace->getUuidForUrl() 'uuid' => $existingPlace->getUuidForUrl()
], true); ], true) . '">cliquez ici pour accéder au formulaire de modification</a>"';
} }
$this->addFlash('success', 'L\'email a été mis à jour. Un email vous sera envoyé avec le lien de modification. ' . $debug); $this->addFlash('success', 'L\'email a été mis à jour. Un email vous sera envoyé avec le lien de modification. ' . $debug);
@ -95,10 +96,10 @@ class PublicController extends AbstractController
$debug = ''; $debug = '';
if ($this->getParameter('kernel.environment') !== 'prod') { if ($this->getParameter('kernel.environment') !== 'prod') {
$debug = 'Bonjour, nous sommes des bénévoles d\'OpenStreetMap France et nous vous proposons de modifier les informations de votre commerce. Voici votre lien unique de modification: ' . $this->generateUrl('app_public_edit', [ $debug = 'Bonjour, nous sommes des bénévoles d\'OpenStreetMap France et nous vous proposons de modifier les informations de votre commerce. Voici votre lien unique de modification: ' . $this->generateUrl('app_public_edit', [
'zipcode' => $zipCode, 'zipcode' => $zipCode,
'name' => $place_name, 'name' => $place_name,
'uuid' => $place->getUuidForUrl() 'uuid' => $place->getUuidForUrl()
], true); ], true);
} }
$this->addFlash('success', 'Un email vous sera envoyé avec le lien de modification. ' . $debug); $this->addFlash('success', 'Un email vous sera envoyé avec le lien de modification. ' . $debug);
} }
@ -111,10 +112,10 @@ class PublicController extends AbstractController
->to($destinataire) ->to($destinataire)
->subject('Votre lien de modification OpenStreetMap') ->subject('Votre lien de modification OpenStreetMap')
->text('Bonjour, nous sommes des bénévoles d\'OpenStreetMap France et nous vous proposons de modifier les informations de votre commerce. Voici votre lien unique de modification: ' . $this->generateUrl('app_public_edit', [ ->text('Bonjour, nous sommes des bénévoles d\'OpenStreetMap France et nous vous proposons de modifier les informations de votre commerce. Voici votre lien unique de modification: ' . $this->generateUrl('app_public_edit', [
'zipcode' => $zipCode, 'zipcode' => $zipCode,
'name' => $place_name, 'name' => $place_name,
'uuid' => $existingPlace ? $existingPlace->getUuidForUrl() : $place->getUuidForUrl() 'uuid' => $existingPlace ? $existingPlace->getUuidForUrl() : $place->getUuidForUrl()
], true)); ], true));
$this->mailer->send($message); $this->mailer->send($message);
@ -195,16 +196,26 @@ class PublicController extends AbstractController
$stats = $stats_exist; $stats = $stats_exist;
} else { } else {
$stats = new Stats(); $stats = new Stats();
$stats->setZone((string)$demande->getInsee()); $zipcode = (string)$demande->getInsee();
$stats->setZone($zipcode);
$place->setZipCode($zipcode);
$this->entityManager->persist($stats); $this->entityManager->persist($stats);
} }
$stats->addPlace($place); $stats->addPlace($place);
$place->setStats($stats); $place->setStats($stats);
} }
} }
} }
if (!$place->getUuidForUrl()) {
$place->setUuidForUrl(uniqid());
}
if (!$place->getZipCode()) {
$place->setZipCode("00000");
}
$this->entityManager->persist($demande); $this->entityManager->persist($demande);
$this->entityManager->flush(); $this->entityManager->flush();
@ -260,8 +271,8 @@ class PublicController extends AbstractController
'name' => $cityName, 'name' => $cityName,
'zone' => $stat->getZone(), 'zone' => $stat->getZone(),
'coordinates' => [ 'coordinates' => [
'lat' => (float) $stat->getLat(), 'lat' => (float)$stat->getLat(),
'lon' => (float) $stat->getLon() 'lon' => (float)$stat->getLon()
], ],
'placesCount' => $stat->getPlacesCount(), 'placesCount' => $stat->getPlacesCount(),
'completionPercent' => $stat->getCompletionPercent(), 'completionPercent' => $stat->getCompletionPercent(),
@ -317,8 +328,8 @@ class PublicController extends AbstractController
if (!empty($data) && isset($data[0]['lat']) && isset($data[0]['lon'])) { 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']); error_log("DEBUG: Coordonnées trouvées pour $cityName ($inseeCode): " . $data[0]['lat'] . ", " . $data[0]['lon']);
return [ return [
'lat' => (float) $data[0]['lat'], 'lat' => (float)$data[0]['lat'],
'lon' => (float) $data[0]['lon'] 'lon' => (float)$data[0]['lon']
]; ];
} else { } else {
error_log("DEBUG: Aucune coordonnée trouvée pour $cityName ($inseeCode)"); error_log("DEBUG: Aucune coordonnée trouvée pour $cityName ($inseeCode)");
@ -901,7 +912,7 @@ class PublicController extends AbstractController
if ($place) { if ($place) {
return $this->redirectToRoute('app_public_edit', [ return $this->redirectToRoute('app_public_edit', [
'zipcode' => $place->getZipCode(), 'zipcode' => $place->getZipCode(),
'name' => $place->getName() !== '' ? $place->getName() : '?', 'name' => $place->getName() ? $place->getName() : '?',
'uuid' => $place->getUuidForUrl() 'uuid' => $place->getUuidForUrl()
]); ]);
} else { } else {
@ -1115,7 +1126,7 @@ class PublicController extends AbstractController
// Trier les changements par date pour chaque thème // Trier les changements par date pour chaque thème
foreach ($themeChanges as &$changes) { foreach ($themeChanges as &$changes) {
usort($changes, function($a, $b) { usort($changes, function ($a, $b) {
return $b->getDate() <=> $a->getDate(); return $b->getDate() <=> $a->getDate();
}); });
} }

View file

@ -7,6 +7,7 @@ use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types; use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
// use App\Service\Motocultrice; // use App\Service\Motocultrice;
#[ORM\Entity(repositoryClass: PlaceRepository::class)] #[ORM\Entity(repositoryClass: PlaceRepository::class)]
class Place class Place
@ -95,11 +96,11 @@ class Place
private ?string $street = null; private ?string $street = null;
#[ORM\Column(length: 255, nullable: true, options: ['charset' #[ORM\Column(length: 255, nullable: true, options: ['charset'
=> 'utf8mb4'])] => 'utf8mb4'])]
private ?string $housenumber = null; private ?string $housenumber = null;
#[ORM\Column(length: 255, nullable: true, options: ['charset' #[ORM\Column(length: 255, nullable: true, options: ['charset'
=> 'utf8mb4'])] => 'utf8mb4'])]
private ?string $siret = null; private ?string $siret = null;
#[ORM\Column(nullable: true)] #[ORM\Column(nullable: true)]
@ -195,29 +196,32 @@ class Place
return round($filled_fields / $total_fields * 100); return round($filled_fields / $total_fields * 100);
} }
public function guess_main_tag(array $tags_converted) { public function guess_main_tag(array $tags_converted)
{
$main_tag = null; $main_tag = null;
if (isset($tags_converted['amenity']) && $tags_converted['amenity'] != '') { if (isset($tags_converted['amenity']) && $tags_converted['amenity'] != '') {
$main_tag = 'amenity='.$tags_converted['amenity']; $main_tag = 'amenity=' . $tags_converted['amenity'];
} }
if (isset($tags_converted['shop']) && $tags_converted['shop'] != '') { if (isset($tags_converted['shop']) && $tags_converted['shop'] != '') {
$main_tag = 'shop='.$tags_converted['shop']; $main_tag = 'shop=' . $tags_converted['shop'];
} }
if (isset($tags_converted['tourism']) && $tags_converted['tourism'] != '') { if (isset($tags_converted['tourism']) && $tags_converted['tourism'] != '') {
$main_tag = 'tourism='.$tags_converted['tourism']; $main_tag = 'tourism=' . $tags_converted['tourism'];
} }
if (isset($tags_converted['office']) && $tags_converted['office'] != '') { if (isset($tags_converted['office']) && $tags_converted['office'] != '') {
$main_tag = 'office='.$tags_converted['office']; $main_tag = 'office=' . $tags_converted['office'];
} }
if (isset($tags_converted['healthcare']) && $tags_converted['healthcare'] != '') { if (isset($tags_converted['healthcare']) && $tags_converted['healthcare'] != '') {
$main_tag = 'healthcare='.$tags_converted['healthcare']; $main_tag = 'healthcare=' . $tags_converted['healthcare'];
} }
return $main_tag; return $main_tag;
} }
/** /**
* mettre à jour le lieu selon les tags osm * mettre à jour le lieu selon les tags osm
*/ */
public function update_place_from_overpass_data(array $overpass_data) { public function update_place_from_overpass_data(array $overpass_data)
{
if (!isset($overpass_data['tags']) || $overpass_data['tags'] == null) { if (!isset($overpass_data['tags']) || $overpass_data['tags'] == null) {
return; return;
@ -228,8 +232,8 @@ class Place
// Setters for basic properties from top-level of overpass data // Setters for basic properties from top-level of overpass data
$this->setOsmId($overpass_data['id']) $this->setOsmId($overpass_data['id'])
->setOsmKind($overpass_data['type']) ->setOsmKind($overpass_data['type'])
->setLat((float) ($overpass_data['lat'] ?? 0)) ->setLat((float)($overpass_data['lat'] ?? 0))
->setLon((float) ($overpass_data['lon'] ?? 0)); ->setLon((float)($overpass_data['lon'] ?? 0));
// Setters for metadata // Setters for metadata
if (isset($overpass_data['timestamp'])) { if (isset($overpass_data['timestamp'])) {
@ -284,7 +288,7 @@ class Place
// has address logic // has address logic
$this->setHasAddress(!empty($this->getStreet()) && !empty($this->getHousenumber()) $this->setHasAddress(!empty($this->getStreet()) && !empty($this->getHousenumber())
| (isset($tags['addr:street']) && isset($tags['addr:housenumber'])) ); | (isset($tags['addr:street']) && isset($tags['addr:housenumber'])));
// has website logic (with multiple possible tags) // has website logic (with multiple possible tags)
$websiteTags = ['website', 'contact:website', 'url', 'contact:url']; $websiteTags = ['website', 'contact:website', 'url', 'contact:url'];
@ -319,6 +323,10 @@ class Place
public function __construct() public function __construct()
{ {
$this->setUuidForUrl(uniqid())
->setDead(false)
->setAskedHumainsSupport(false)
->setOptedOut(false);
$this->histories = new ArrayCollection(); $this->histories = new ArrayCollection();
} }

View file

@ -21,7 +21,13 @@
{% if main_tag %} {% if main_tag %}
{{ tag_emoji(main_tag) }} {{ tag_emoji(main_tag) }}
{% endif %} {% endif %}
{{ commerce_overpass.tags_converted.name }} - {{ commerce.stats.name }} {% if commerce_overpass.tags_converted.name is defined %}
{{ commerce_overpass.tags_converted.name }}
{% endif %}
{% if commerce.stats.name is defined %}
- {{ commerce.stats.name }}
{% endif %}
</h1> </h1>
<div id="map" style="height: 400px; width: 100%;" class="rounded mb-4"></div> <div id="map" style="height: 400px; width: 100%;" class="rounded mb-4"></div>
@ -54,12 +60,12 @@
<i class="bi bi-phone me-2"></i> <i class="bi bi-phone me-2"></i>
Téléphone Téléphone
</span> </span>
<input type="text" class="form-control" <input type="text" class="form-control"
id="commerce_tag_value__contact:phone" id="commerce_tag_value__contact:phone"
name="commerce_tag_value__contact:phone" name="commerce_tag_value__contact:phone"
data-important="true" data-important="true"
value="{{ commerce_overpass.tags_converted['contact:phone'] ?? '' }}" value="{{ commerce_overpass.tags_converted['contact:phone'] ?? '' }}"
placeholder="+33 1 23 45 67 89"> placeholder="+33 1 23 45 67 89">
</div> </div>
</fieldset> </fieldset>
@ -75,7 +81,9 @@
<div class="input-group"> <div class="input-group">
<input type="text" class="form-control" <input type="text" class="form-control"
data-important="true" data-important="true"
id="commerce_tag_value__contact:email" name="commerce_tag_value__contact:email" value="{{ commerce_overpass.tags_converted['contact:email'] ?? '' }}"> id="commerce_tag_value__contact:email"
name="commerce_tag_value__contact:email"
value="{{ commerce_overpass.tags_converted['contact:email'] ?? '' }}">
</div> </div>
</div> </div>
</div> </div>
@ -92,7 +100,9 @@
<div class="input-group"> <div class="input-group">
<input type="text" class="form-control" <input type="text" class="form-control"
data-important="true" data-important="true"
id="commerce_tag_value__contact:website" name="commerce_tag_value__contact:website" value="{{ commerce_overpass.tags_converted['contact:website'] ?? '' }}"> id="commerce_tag_value__contact:website"
name="commerce_tag_value__contact:website"
value="{{ commerce_overpass.tags_converted['contact:website'] ?? '' }}">
</div> </div>
</div> </div>
</div> </div>
@ -110,7 +120,8 @@
<div class="input-group"> <div class="input-group">
<input type="text" class="form-control" <input type="text" class="form-control"
data-important="true" data-important="true"
id="commerce_tag_value__contact:mastodon" name="commerce_tag_value__contact:mastodon" value=""> id="commerce_tag_value__contact:mastodon"
name="commerce_tag_value__contact:mastodon" value="">
</div> </div>
</div> </div>
</div> </div>
@ -185,16 +196,16 @@
{% include 'public/edit/tags.html.twig' %} {% include 'public/edit/tags.html.twig' %}
{# <div class="mb-4" id="previsualisation_tags">#} {# <div class="mb-4" id="previsualisation_tags"> #}
{# <h4>Prévisualisation des tags OSM (texte à copier-coller)</h4>#} {# <h4>Prévisualisation des tags OSM (texte à copier-coller)</h4> #}
{# {% set tags_for_textarea = {} %}#} {# {% set tags_for_textarea = {} %} #}
{# {% for k, v in commerce_overpass.tags_converted %}#} {# {% for k, v in commerce_overpass.tags_converted %} #}
{# {% if v is not empty %}#} {# {% if v is not empty %} #}
{# {% set tags_for_textarea = tags_for_textarea|merge({ (k): v }) %}#} {# {% set tags_for_textarea = tags_for_textarea|merge({ (k): v }) %} #}
{# {% endif %}#} {# {% endif %} #}
{# {% endfor %}#} {# {% endfor %} #}
{# {% include 'public/_tags_textarea.html.twig' with { 'tags': tags_for_textarea } %}#} {# {% include 'public/_tags_textarea.html.twig' with { 'tags': tags_for_textarea } %} #}
{# </div>#} {# </div> #}
<div id="validation_messages" class="alert alert-danger d-none"></div> <div id="validation_messages" class="alert alert-danger d-none"></div>
<div class="d-grid gap-2 d-md-flex justify-content-md-end mt-4"> <div class="d-grid gap-2 d-md-flex justify-content-md-end mt-4">
@ -313,197 +324,197 @@
<script src='{{ asset('js/utils.js') }}'></script> <script src='{{ asset('js/utils.js') }}'></script>
<script> <script>
{% 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 %} {% 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 }}'; mapboxgl.accessToken = '{{ mapbox_token }}';
let map = new mapboxgl.Map({ let map = new mapboxgl.Map({
container: 'map', container: 'map',
style: 'https://api.maptiler.com/maps/basic-v2/style.json?key={{ maptiler_token }}', style: 'https://api.maptiler.com/maps/basic-v2/style.json?key={{ maptiler_token }}',
center: [{{ commerce_overpass['@attributes'].lon }}, {{ commerce_overpass['@attributes'].lat }}], center: [{{ commerce_overpass['@attributes'].lon }}, {{ commerce_overpass['@attributes'].lat }}],
zoom: 17 zoom: 17
}); });
new mapboxgl.Marker() new mapboxgl.Marker()
.setLngLat([{{ commerce_overpass['@attributes'].lon }}, {{ commerce_overpass['@attributes'].lat }}]) .setLngLat([{{ commerce_overpass['@attributes'].lon }}, {{ commerce_overpass['@attributes'].lat }}])
.setPopup(new mapboxgl.Popup({offset: 25}).setHTML('<h1>{{ commerce_overpass.tags_converted.name }}</h1>')) .setPopup(new mapboxgl.Popup({offset: 25}).setHTML('<h1>{{ commerce_overpass.tags_converted.name }}</h1>'))
.addTo(map); .addTo(map);
{% endif %} {% endif %}
// Ajouter un écouteur d'événement pour le redimensionnement de la fenêtre // Ajouter un écouteur d'événement pour le redimensionnement de la fenêtre
window.addEventListener('resize', () => { window.addEventListener('resize', () => {
updateMapHeightForLargeScreens(); updateMapHeightForLargeScreens();
}); });
/** /**
* indiquer la complétion des champs importants dans ce formulaire * indiquer la complétion des champs importants dans ce formulaire
* @param e * @param e
*/ */
function check_validity(e) { function check_validity(e) {
list_inputs_good_to_fill = [ list_inputs_good_to_fill = [
'input[name="commerce_tag_value__name"]', 'input[name="commerce_tag_value__name"]',
'input[name="commerce_tag_value__contact:email"]', 'input[name="commerce_tag_value__contact:email"]',
'input[name="commerce_tag_value__contact:phone"]', 'input[name="commerce_tag_value__contact:phone"]',
'input[name="commerce_tag_value__contact:website"]', 'input[name="commerce_tag_value__contact:website"]',
'input[name="commerce_tag_value__contact:mastodon"]', 'input[name="commerce_tag_value__contact:mastodon"]',
'input[name="commerce_tag_value__address"]', 'input[name="commerce_tag_value__address"]',
'input[name="custom_opening_hours"]', 'input[name="custom_opening_hours"]',
'input[name="commerce_tag_value__contact:street"]', 'input[name="commerce_tag_value__contact:street"]',
'input[name="commerce_tag_value__contact:housenumber"]', 'input[name="commerce_tag_value__contact:housenumber"]',
'input[name="custom__cuisine"]', 'input[name="custom__cuisine"]',
] ]
list_inputs_good_to_fill.forEach(selector => { list_inputs_good_to_fill.forEach(selector => {
const input = document.querySelector(selector); const input = document.querySelector(selector);
if (input) { if (input) {
if (input.value.trim() !== '') { if (input.value.trim() !== '') {
input.classList.add('good_filled'); input.classList.add('good_filled');
} else { } else {
input.classList.remove('good_filled'); input.classList.remove('good_filled');
} }
} }
}); });
let errors = []; let errors = [];
document.querySelectorAll('.is-invalid').forEach(input => { document.querySelectorAll('.is-invalid').forEach(input => {
input.classList.remove('is-invalid'); input.classList.remove('is-invalid');
}); });
const nameInput = document.querySelector('input[name="commerce_tag_value__name"]'); const nameInput = document.querySelector('input[name="commerce_tag_value__name"]');
if (!nameInput.value.trim()) { if (!nameInput.value.trim()) {
errors.push("Le nom de l'établissement est obligatoire"); errors.push("Le nom de l'établissement est obligatoire");
nameInput.classList.add('is-invalid'); nameInput.classList.add('is-invalid');
} }
const emailInput = document.querySelector('input[name="commerce_tag_value__contact:email"]'); const emailInput = document.querySelector('input[name="commerce_tag_value__contact:email"]');
if (emailInput && emailInput.value) { if (emailInput && emailInput.value) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(emailInput.value)) { if (!emailRegex.test(emailInput.value)) {
errors.push("L'adresse email n'est pas valide"); errors.push("L'adresse email n'est pas valide");
emailInput.classList.add('is-invalid'); emailInput.classList.add('is-invalid');
} }
} }
const phoneInput = document.querySelector('input[name="commerce_tag_value__contact:phone"]'); const phoneInput = document.querySelector('input[name="commerce_tag_value__contact:phone"]');
if (phoneInput && phoneInput.value) { if (phoneInput && phoneInput.value) {
const phoneRegex = /^(\+33|0)[1-9](\d{2}){4}$/; const phoneRegex = /^(\+33|0)[1-9](\d{2}){4}$/;
if (!phoneRegex.test(phoneInput.value.replace(/\s/g, ''))) { if (!phoneRegex.test(phoneInput.value.replace(/\s/g, ''))) {
errors.push("Le numéro de téléphone n'est pas valide"); errors.push("Le numéro de téléphone n'est pas valide");
phoneInput.classList.add('is-invalid'); phoneInput.classList.add('is-invalid');
} }
} }
// Collect all missing important fields // Collect all missing important fields
const missingImportantFields = []; const missingImportantFields = [];
list_inputs_good_to_fill.forEach(selector => { list_inputs_good_to_fill.forEach(selector => {
const input = document.querySelector(selector); const input = document.querySelector(selector);
if (input && input.value.trim() === '') { if (input && input.value.trim() === '') {
// Get the field label or name for display // Get the field label or name for display
let fieldName = ''; let fieldName = '';
const label = input.closest('.row')?.querySelector('.form-label, .label-translated'); const label = input.closest('.row')?.querySelector('.form-label, .label-translated');
if (label) { if (label) {
fieldName = label.textContent.trim(); fieldName = label.textContent.trim();
} else { } else {
// If no label found, try to get a meaningful name from the input // If no label found, try to get a meaningful name from the input
const name = input.getAttribute('name'); const name = input.getAttribute('name');
if (name) { if (name) {
// Extract field name from the attribute (e.g., commerce_tag_value__contact:email -> Email) // Extract field name from the attribute (e.g., commerce_tag_value__contact:email -> Email)
const parts = name.split('__'); const parts = name.split('__');
if (parts.length > 1) { if (parts.length > 1) {
fieldName = parts[1].replace('commerce_tag_value_', '').replace('contact:', ''); fieldName = parts[1].replace('commerce_tag_value_', '').replace('contact:', '');
// Capitalize first letter // Capitalize first letter
fieldName = fieldName.charAt(0).toUpperCase() + fieldName.slice(1); fieldName = fieldName.charAt(0).toUpperCase() + fieldName.slice(1);
} else { } else {
fieldName = name; fieldName = name;
} }
} }
} }
missingImportantFields.push(fieldName || input.getAttribute('name') || 'Champ inconnu'); missingImportantFields.push(fieldName || input.getAttribute('name') || 'Champ inconnu');
} }
}); });
if (errors.length > 0 || missingImportantFields.length > 0) { if (errors.length > 0 || missingImportantFields.length > 0) {
e.preventDefault(); e.preventDefault();
// Format missing fields as an HTML list for better readability // Format missing fields as an HTML list for better readability
let missingFieldsContent = ''; let missingFieldsContent = '';
if (missingImportantFields.length > 0) { if (missingImportantFields.length > 0) {
// Filter out empty or undefined field names and sort them alphabetically // Filter out empty or undefined field names and sort them alphabetically
const filteredMissingFields = missingImportantFields const filteredMissingFields = missingImportantFields
.filter(field => field && field.trim() !== '') .filter(field => field && field.trim() !== '')
.sort(); .sort();
// Create the HTML content for the popover // Create the HTML content for the popover
missingFieldsContent = '<ul class="list-unstyled mb-0">'; missingFieldsContent = '<ul class="list-unstyled mb-0">';
filteredMissingFields.forEach(field => { filteredMissingFields.forEach(field => {
missingFieldsContent += `<li><i class="bi bi-exclamation-circle text-warning"></i> ${field}</li>`; missingFieldsContent += `<li><i class="bi bi-exclamation-circle text-warning"></i> ${field}</li>`;
}); });
missingFieldsContent += '</ul>'; missingFieldsContent += '</ul>';
} }
// Display validation errors // Display validation errors
let validationMessage = ''; let validationMessage = '';
if (errors.length > 0) { if (errors.length > 0) {
validationMessage += errors.join('<br>'); validationMessage += errors.join('<br>');
} }
// Add information about missing fields with a popover // Add information about missing fields with a popover
if (missingImportantFields.length > 0) { if (missingImportantFields.length > 0) {
if (validationMessage) { if (validationMessage) {
validationMessage += '<br>'; validationMessage += '<br>';
} }
validationMessage += `Champs manquants: ${missingImportantFields.length} <a href="#" class="missing-fields-info badge rounded-pill bg-warning text-dark ms-1" style="text-decoration: none; font-weight: bold;" data-bs-toggle="popover" data-bs-placement="bottom" title="Champs manquants" data-bs-html="true" data-bs-content="${missingFieldsContent.replace(/"/g, '&quot;')}">?</a>`; validationMessage += `Champs manquants: ${missingImportantFields.length} <a href="#" class="missing-fields-info badge rounded-pill bg-warning text-dark ms-1" style="text-decoration: none; font-weight: bold;" data-bs-toggle="popover" data-bs-placement="bottom" title="Champs manquants" data-bs-html="true" data-bs-content="${missingFieldsContent.replace(/"/g, '&quot;')}">?</a>`;
} }
document.querySelector('#validation_messages').innerHTML = validationMessage; document.querySelector('#validation_messages').innerHTML = validationMessage;
document.querySelector('#validation_messages').classList.remove('d-none'); document.querySelector('#validation_messages').classList.remove('d-none');
document.querySelector('#validation_messages').classList.add('is-invalid'); document.querySelector('#validation_messages').classList.add('is-invalid');
// Initialize the Bootstrap popover // Initialize the Bootstrap popover
const popoverTrigger = document.querySelector('.missing-fields-info'); const popoverTrigger = document.querySelector('.missing-fields-info');
if (popoverTrigger) { if (popoverTrigger) {
// Add click handler to focus on the first missing field // Add click handler to focus on the first missing field
popoverTrigger.addEventListener('click', function(e) { popoverTrigger.addEventListener('click', function (e) {
e.preventDefault(); // Prevent scrolling to top e.preventDefault(); // Prevent scrolling to top
// Find the first missing field from the list_inputs_good_to_fill // Find the first missing field from the list_inputs_good_to_fill
let firstMissingField = null; let firstMissingField = null;
for (const selector of list_inputs_good_to_fill) { for (const selector of list_inputs_good_to_fill) {
const input = document.querySelector(selector); const input = document.querySelector(selector);
if (input && input.value.trim() === '') { if (input && input.value.trim() === '') {
firstMissingField = input; firstMissingField = input;
break; break;
} }
} }
if (firstMissingField) { if (firstMissingField) {
// Focus on the first missing field // Focus on the first missing field
firstMissingField.focus(); firstMissingField.focus();
// Scroll to the field if needed // Scroll to the field if needed
firstMissingField.scrollIntoView({ behavior: 'smooth', block: 'center' }); firstMissingField.scrollIntoView({behavior: 'smooth', block: 'center'});
} }
}); });
// Use setTimeout to ensure this runs after the current execution context // Use setTimeout to ensure this runs after the current execution context
setTimeout(() => { setTimeout(() => {
if (typeof bootstrap !== 'undefined' && bootstrap.Popover) { if (typeof bootstrap !== 'undefined' && bootstrap.Popover) {
// Destroy existing popover if any // Destroy existing popover if any
const existingPopover = bootstrap.Popover.getInstance(popoverTrigger); const existingPopover = bootstrap.Popover.getInstance(popoverTrigger);
if (existingPopover) { if (existingPopover) {
existingPopover.dispose(); existingPopover.dispose();
} }
// Initialize new popover // Initialize new popover
new bootstrap.Popover(popoverTrigger, { new bootstrap.Popover(popoverTrigger, {
html: true, html: true,
trigger: 'click', trigger: 'click',
container: 'body' container: 'body'
}); });
} }
}, 0); }, 0);
} }
} }
} }
check_validity ? check_validity() : null; check_validity ? check_validity() : null;
</script> </script>
{% endblock %} {% endblock %}