Skip to content

Commit

Permalink
Merge pull request #417 from MTES-MCT/feature/guh-flechage
Browse files Browse the repository at this point in the history
Feature/guh flechage
  • Loading branch information
pyDez authored Sep 27, 2024
2 parents aa4b256 + f1f767c commit 8d0bb3e
Show file tree
Hide file tree
Showing 25 changed files with 383 additions and 93 deletions.
5 changes: 4 additions & 1 deletion config/tests/test_urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ def site() -> Site:
"moulinette_result",
]

HAIE_URLS = []
HAIE_URLS = [
"triage",
"triage_result",
]

AMENAGEMENT_URLS = [
# "/avis",
Expand Down
2 changes: 1 addition & 1 deletion config/urls_amenagement.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
path("evaluations/", include("envergo.evaluations.redirect_urls")),
path("évaluations/", include("envergo.evaluations.redirect_urls")),
path("avis/", include("envergo.evaluations.urls")),
path(_("moulinette/"), include("envergo.moulinette.urls")),
path(_("moulinette/"), include("envergo.moulinette.urls_amenagement")),
path(_("geo/"), include("envergo.geodata.urls")),
path("demonstrateur-bv/", CatchmentAreaDebug.as_view(), name="2150_debug"),
] + common_urlpatterns
6 changes: 1 addition & 5 deletions config/urls_haie.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
from django.urls import include, path
from django.utils.translation import gettext_lazy as _

from .urls import urlpatterns as common_urlpatterns

urlpatterns = [
path("", include("envergo.pages.urls_haie")),
path(
"indre/",
include([path(_("moulinette/"), include("envergo.moulinette.urls"))]),
),
path("indre/", include("envergo.moulinette.urls_haie")),
] + common_urlpatterns
59 changes: 59 additions & 0 deletions envergo/moulinette/forms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _

from envergo.geodata.models import DEPARTMENT_CHOICES
from envergo.moulinette.forms.fields import (
DisplayCharField,
DisplayChoiceField,
DisplayIntegerField,
extract_choices,
Expand Down Expand Up @@ -186,6 +188,15 @@ class MoulinetteFormHaie(BaseMoulinetteForm):
get_display_value=extract_display_function(REIMPLANTATION_CHOICES),
)

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
submitted_params = set(self.data.keys())
triage_fields = set(TriageFormHaie.base_fields.keys())

# Check if only the Triage form fields are submitted
if submitted_params.issubset(triage_fields):
self.is_bound = False

def clean(self):
data = super().clean()

Expand All @@ -212,3 +223,51 @@ def clean(self):
)

return data


class TriageFormHaie(forms.Form):
department = DisplayCharField(
label="Département",
required=True,
initial="36",
get_display_value=lambda x: dict(DEPARTMENT_CHOICES).get(x, "Inconnu"),
)
element = DisplayChoiceField(
label="Quel élément paysager est concerné ?",
widget=forms.RadioSelect,
choices=(
("haie", "Une haie"),
("bosquet", "Un bosquet"),
("alignement", "Un alignement d'arbres"),
(
"autre",
"Autre",
),
),
required=True,
display_label="Élément paysager :",
)

travaux = DisplayChoiceField(
label="Quels sont les travaux envisagés ?",
widget=forms.RadioSelect,
choices=(
(
"arrachage",
mark_safe(
"Arrachage<br />"
'<span class="fr-hint-text">Toute intervention impliquant l\'enlèvement des souches</span>'
),
),
(
"entretien",
"Entretien",
),
(
"autre",
"Autre",
),
),
required=True,
display_label="Travaux envisagés :",
)
4 changes: 4 additions & 0 deletions envergo/moulinette/forms/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ class DisplayIntegerField(DisplayFieldMixin, forms.IntegerField):
pass


class DisplayCharField(DisplayFieldMixin, forms.CharField):
pass


def extract_choices(choices):
"""Extract form choices from a list of 3 items tuples : code, form label, display label."""
return [(code, form_label) for code, form_label, _ in choices]
Expand Down
45 changes: 44 additions & 1 deletion envergo/moulinette/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from django.db.models import When
from django.db.models.functions import Cast, Concat
from django.http import QueryDict
from django.urls import reverse
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from model_utils import Choices
Expand All @@ -22,9 +23,14 @@
from envergo.evaluations.models import RESULTS
from envergo.geodata.models import Department, Zone
from envergo.moulinette.fields import CriterionEvaluatorChoiceField
from envergo.moulinette.forms import MoulinetteFormAmenagement, MoulinetteFormHaie
from envergo.moulinette.forms import (
MoulinetteFormAmenagement,
MoulinetteFormHaie,
TriageFormHaie,
)
from envergo.moulinette.regulations import Map, MapPolygon
from envergo.moulinette.utils import list_moulinette_templates
from envergo.utils.urls import update_qs

# WGS84, geodetic coordinates, units in degrees
# Good for storing data and working wordwide
Expand Down Expand Up @@ -1126,6 +1132,20 @@ def get_debug_context(self):
"""Add some data to display on the debug page"""
raise NotImplementedError

@classmethod
@abstractmethod
def get_triage_params(cls):
"""Add some data to display on the debug page"""
raise NotImplementedError

@classmethod
def get_extra_context(cls, request):
"""return extra context data for the moulinette views.
You can use this method to add some context specific to your site : Haie or Amenagement
"""

return {}


class MoulinetteAmenagement(Moulinette):
REGULATIONS = ["loi_sur_leau", "natura2000", "eval_env", "sage"]
Expand Down Expand Up @@ -1349,6 +1369,10 @@ def get_debug_context(self):
),
}

@classmethod
def get_triage_params(cls):
return set()


class MoulinetteHaie(Moulinette):
REGULATIONS = ["conditionnalite_pac", "dep"]
Expand Down Expand Up @@ -1382,6 +1406,25 @@ def load_specific_data(self):
def get_debug_context(self):
return {}

@classmethod
def get_triage_params(cls):
return set(TriageFormHaie.base_fields.keys())

@classmethod
def get_extra_context(cls, request):
"""return extra context data for the moulinette views.
You can use this method to add some context specific to your site : Haie or Amenagement
"""
context = {}
form_data = request.GET
context["triage_url"] = update_qs(reverse("triage"), form_data)
triage_form = TriageFormHaie(data=form_data)
if triage_form.is_valid():
context["triage_form"] = triage_form
else:
context["redirect_url"] = context["triage_url"]
return context


def get_moulinette_class_from_site(site):
"""Return the correct Moulinette class depending on the current site."""
Expand Down
3 changes: 3 additions & 0 deletions envergo/moulinette/urls_amenagement.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .urls import urlpatterns as common_urlpatterns

urlpatterns = [] + common_urlpatterns
18 changes: 18 additions & 0 deletions envergo/moulinette/urls_haie.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from django.urls import include, path
from django.utils.translation import gettext_lazy as _

from envergo.moulinette.views import Triage, TriageResult

urlpatterns = [
path(
"",
Triage.as_view(),
name="triage",
),
path(
_("result/"),
TriageResult.as_view(),
name="triage_result",
),
path(_("moulinette/"), include("envergo.moulinette.urls")),
]
75 changes: 68 additions & 7 deletions envergo/moulinette/views.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import json
from collections import OrderedDict
from urllib.parse import parse_qs, urlparse
from urllib.parse import parse_qs, urlencode, urlparse

from django.conf import settings
from django.http import HttpResponseRedirect, QueryDict
from django.urls import reverse
from django.views.generic import FormView
from django.views.generic import FormView, TemplateView

from envergo.analytics.forms import FeedbackFormUseful, FeedbackFormUseless
from envergo.analytics.utils import is_request_from_a_bot, log_event
from envergo.evaluations.models import RESULTS
from envergo.geodata.utils import get_address_from_coords
from envergo.moulinette.forms import TriageFormHaie
from envergo.moulinette.models import get_moulinette_class_from_site
from envergo.moulinette.utils import compute_surfaces
from envergo.utils.urls import extract_mtm_params, remove_from_qs, update_qs
Expand Down Expand Up @@ -74,10 +75,10 @@ def get_moulinette_raw_data(self):

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
MoulinetteClass = get_moulinette_class_from_site(self.request.site)

form = context["form"]
if form.is_valid():
MoulinetteClass = get_moulinette_class_from_site(self.request.site)
moulinette = MoulinetteClass(
form.cleaned_data, form.data, self.should_activate_optional_criteria()
)
Expand Down Expand Up @@ -135,6 +136,8 @@ def get_context_data(self, **kwargs):
context.get("moulinette", None)
)

context = {**context, **MoulinetteClass.get_extra_context(self.request)}

return context

def render_to_response(self, context, **response_kwargs):
Expand Down Expand Up @@ -256,6 +259,12 @@ def get_results_url(self, form):
field.html_name, optional_form.data.getlist(field.html_name)
)

triage_params = moulinette.get_triage_params()
if triage_params:
get.update(
{key: form.data[key] for key in triage_params if key in form.data}
)

url_params = get.urlencode()
url = reverse("moulinette_result")

Expand Down Expand Up @@ -291,7 +300,10 @@ class MoulinetteHome(MoulinetteMixin, FormView):
def get(self, request, *args, **kwargs):
context = self.get_context_data()
res = self.render_to_response(context)
if self.moulinette:

if "redirect_url" in context:
return HttpResponseRedirect(context["redirect_url"])
elif self.moulinette:
return HttpResponseRedirect(self.get_results_url(context["form"]))
else:
return res
Expand Down Expand Up @@ -331,7 +343,10 @@ def get(self, request, *args, **kwargs):
context = self.get_context_data()
res = self.render_to_response(context)
moulinette = self.moulinette
if moulinette:

if "redirect_url" in context:
return HttpResponseRedirect(context["redirect_url"])
elif moulinette:
if (
"debug" not in self.request.GET
and not is_edit
Expand Down Expand Up @@ -369,7 +384,6 @@ def validate_results_url(self, request, context):

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)

# Let's build custom uris for better matomo tracking
# Depending on the moulinette result, we want to track different uris
# as if they were distinct pages.
Expand All @@ -379,7 +393,6 @@ def get_context_data(self, **kwargs):
debug_result_url = update_qs(current_url, {"debug": "true"})
result_url = remove_from_qs(current_url, "debug")
edit_url = update_qs(result_url, {"edit": "true"})

# Url without any query parameters
# We want to build "fake" urls for matomo tracking
# For example, if the current url is /simulateur/resultat/?debug=true,
Expand Down Expand Up @@ -449,3 +462,51 @@ def get_context_data(self, **kwargs):
context["edit_url"] = edit_url

return context


class Triage(FormView):
form_class = TriageFormHaie
template_name = "haie/moulinette/triage.html"

def get_initial(self):
"""Populate the form with data from the query string."""
return self.request.GET.dict()

def form_valid(self, form):
query_params = form.cleaned_data
if query_params["element"] == "haie" and query_params["travaux"] == "arrachage":
url = reverse("moulinette_home")
else:
url = reverse("triage_result")

query_string = urlencode(query_params)
url_with_params = f"{url}?{query_string}"
return HttpResponseRedirect(url_with_params)


class TriageResult(TemplateView):
template_name = "haie/moulinette/triage_result.html"

def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
form = context["form"]
if not form.is_valid():
return HttpResponseRedirect(reverse("triage"))
return self.render_to_response(context)

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
form_data = self.request.GET
context["form"] = TriageFormHaie(data=form_data)

envergo_url = self.request.build_absolute_uri("/")
current_url = self.request.build_absolute_uri()
share_print_url = update_qs(current_url, {"mtm_campaign": "print-simu"})
edit_url = update_qs(reverse("triage"), form_data)

context["current_url"] = current_url
context["share_print_url"] = share_print_url
context["envergo_url"] = envergo_url
context["edit_url"] = edit_url

return context
Loading

0 comments on commit 8d0bb3e

Please sign in to comment.