Skip to content

Commit

Permalink
Merge pull request #416 from MTES-MCT/analytics_mtm_keywords
Browse files Browse the repository at this point in the history
Conserve les paramètres analytics dans l'url
  • Loading branch information
pyDez authored Sep 13, 2024
2 parents e52dfe3 + 25a11b0 commit 4009684
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 8 deletions.
42 changes: 40 additions & 2 deletions envergo/moulinette/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,13 +111,51 @@ def test_moulinette_result_without_params_redirects_to_home(client):


def test_moulinette_result_form_error(client):
"""Bad params are cleaned from the result url."""

MoulinetteConfigFactory()

url = reverse("moulinette_result")
params = "bad_param=true"
params = (
"created_surface=500&final_surface=500&lng=-1.54394&lat=47.21381&bad_param=true"
)
full_url = f"{url}?{params}"
res = client.get(full_url)

assert res.status_code == 302
assert res.url.endswith("/simulateur/formulaire/")
assert (
res.url
== "/simulateur/resultat/?created_surface=500&final_surface=500&lng=-1.54394&lat=47.21381"
)


def test_moulinette_result_mtm_keywords_are_not_bad_params(client):
"""Analytics params are not cleaned from the result url."""
MoulinetteConfigFactory(is_activated=True)

url = reverse("moulinette_result")
params = "created_surface=500&final_surface=500&lng=-1.54394&lat=47.21381&mtm_campaign=test"
full_url = f"{url}?{params}"
res = client.get(full_url)

assert res.status_code == 200
assertTemplateUsed(res, "moulinette/result.html")


def test_moulinette_result_custom_matomo_tracking_url(client):
MoulinetteConfigFactory(is_activated=True)

url = reverse("moulinette_result")
params = "created_surface=500&final_surface=500&lng=-1.54394&lat=47.21381&mtm_campaign=test"
full_url = f"{url}?{params}"
res = client.get(full_url)

assert res.status_code == 200
content = res.content.decode()
assert (
'var MATOMO_CUSTOM_URL = "http://testserver/simulateur/resultat/?mtm_campaign=test";'
in content
)


def test_moulinette_home_form_error(client):
Expand Down
28 changes: 22 additions & 6 deletions envergo/moulinette/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from envergo.geodata.utils import get_address_from_coords
from envergo.moulinette.models import get_moulinette_class_from_site
from envergo.moulinette.utils import compute_surfaces
from envergo.utils.urls import remove_from_qs, update_qs
from envergo.utils.urls import extract_mtm_params, remove_from_qs, update_qs

BODY_TPL = {
RESULTS.soumis: "moulinette/eval_body_soumis.html",
Expand Down Expand Up @@ -332,7 +332,6 @@ def get(self, request, *args, **kwargs):
res = self.render_to_response(context)
moulinette = self.moulinette
if moulinette:

if (
"debug" not in self.request.GET
and not is_edit
Expand Down Expand Up @@ -362,6 +361,10 @@ def validate_results_url(self, request, context):
current_url = request.get_full_path()
current_qs = parse_qs(urlparse(current_url).query)
current_params = set(current_qs.keys())

# We don't want to take analytics params into account, so they stay in the url
current_params = set([p for p in current_params if not p.startswith("mtm_")])

return expected_params == current_params

def get_context_data(self, **kwargs):
Expand All @@ -378,13 +381,23 @@ def get_context_data(self, **kwargs):
edit_url = update_qs(result_url, {"edit": "true"})

# Url without any query parameters
stripped_url = self.request.build_absolute_uri(self.request.path)
# We want to build "fake" urls for matomo tracking
# For example, if the current url is /simulateur/resultat/?debug=true,
# We want to track this as a custom url /simulateur/debug/
mtm_params = extract_mtm_params(current_url)

# We want to log the current simulation url stripped from any query parameters
# except for mtm_ ones
bare_url = self.request.build_absolute_uri(self.request.path)
matomo_bare_url = update_qs(bare_url, mtm_params)
debug_url = self.request.build_absolute_uri(reverse("moulinette_result_debug"))
matomo_debug_url = update_qs(debug_url, mtm_params)
missing_data_url = self.request.build_absolute_uri(
reverse("moulinette_missing_data")
)
form_url = self.request.build_absolute_uri(reverse("moulinette_home"))
form_url_with_edit = update_qs(form_url, {"edit": "true"})
matomo_missing_data_url = update_qs(missing_data_url, mtm_params)

context["current_url"] = current_url
context["share_btn_url"] = share_btn_url
Expand All @@ -404,14 +417,17 @@ def get_context_data(self, **kwargs):
context = {
**context,
**moulinette.get_debug_context(),
"matomo_custom_url": debug_url,
"result_url": result_url,
"matomo_custom_url": matomo_debug_url,
}

# TODO This cannot happen, since we redirect to the form if data is missing
# Check that it can be safely removed
elif moulinette and moulinette.has_missing_data():
context["matomo_custom_url"] = missing_data_url
context["matomo_custom_url"] = matomo_missing_data_url

elif moulinette:
context["matomo_custom_url"] = stripped_url
context["matomo_custom_url"] = matomo_bare_url
if moulinette.has_config() and moulinette.is_evaluation_available():
context["debug_url"] = debug_result_url

Expand Down
9 changes: 9 additions & 0 deletions envergo/utils/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,12 @@ def remove_from_qs(url, key):
new_query = urlencode(query, doseq=True)
new_bits = bits._replace(query=new_query)
return urlunsplit(new_bits)


def extract_mtm_params(url):
"""Extract mtm parameters from an url."""

bits = urlsplit(url)
query = parse_qs(bits.query)
mtm_params = {k: v for k, v in query.items() if k.startswith("mtm_")}
return mtm_params

0 comments on commit 4009684

Please sign in to comment.