Skip to content

Commit

Permalink
Ajout du formulaire de contact dans l'assistant (#1190)
Browse files Browse the repository at this point in the history
* Ajout du formulaire de contact dans l'assistant

* Update template

* Prepare ntion calls

* Fix Notion payload on form submission

* Format

* Update core/notion.py

Co-authored-by: Nicolas Oudard <[email protected]>

---------

Co-authored-by: Nicolas Oudard <[email protected]>
  • Loading branch information
fabienheureux and kolok authored Jan 21, 2025
1 parent b7ee1ec commit 856efc2
Show file tree
Hide file tree
Showing 8 changed files with 147 additions and 4 deletions.
2 changes: 2 additions & 0 deletions .env.template
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,5 @@ STIMULUS_DEBUG=false
POSTHOG_DEBUG=false
ASSISTANT_MATOMO_ID=82
ASSISTANT_POSTHOG_KEY=phc_fSfhoWDOUxZdKWty16Z3XfRiAoWd1qdJK0N0z9kQHJr # [DEV] project
NOTION_TOKEN=
NOTION_CONTACT_FORM_DATABASE_ID=17c6523d57d78140b87f000cd3ecef4b # Correspond à https://www.notion.so/accelerateur-transition-ecologique-ademe/17c6523d57d7808b8cc5f5ccae264f7c?v=17c6523d57d78140b87f000cd3ecef4b&pvs=4
40 changes: 40 additions & 0 deletions core/notion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import logging

import requests
from django.conf import settings
from django.utils import timezone

logger = logging.getLogger(__name__)


def create_new_row_in_notion_table(database_id, data):
notion_token = settings.NOTION.get("TOKEN")
if not notion_token:
logging.error("The notion token is not set in local environment")
return

headers = {
"Authorization": f"Bearer {notion_token}",
"Content-Type": "application/json",
"Notion-Version": "2022-06-28",
}

payload = {
"parent": {"database_id": database_id},
"properties": {
"Nom": {"title": [{"text": {"content": data.get("name")}}]},
"Email": {"email": data.get("email")},
"Objet": {"rich_text": [{"text": {"content": data.get("subject")}}]},
"Message": {"rich_text": [{"text": {"content": data.get("message")}}]},
"Date": {"date": {"start": timezone.now().isoformat()}},
},
}

response = requests.post(
"https://api.notion.com/v1/pages", headers=headers, json=payload
)

if response.status_code == 200:
logger.info("New contact form submission")
else:
logger.error(f"Failed to add row:{response.status_code=}, {response.text=}")
7 changes: 7 additions & 0 deletions core/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -388,3 +388,10 @@ def context_processors():
cast=str,
),
}

NOTION = {
"TOKEN": decouple.config("NOTION_TOKEN", default=""),
"CONTACT_FORM_DATABASE_ID": decouple.config(
"NOTION_CONTACT_FORM_DATABASE_ID", default=""
),
}
36 changes: 36 additions & 0 deletions qfdmd/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,39 @@ def search(self) -> dict[str, str]:
.values("slug", "nom")[:10]
)
return self.results


class ContactForm(DsfrBaseForm):
name = forms.CharField(label="Votre nom")
email = forms.EmailField(label="Votre email")
subject = forms.ChoiceField(
label="Votre sujet",
choices=[
("", ""),
(
"integration",
"Je souhaite obtenir de l'aide pour intégrer le simulateur",
),
(
"erreur",
"Je souhaite signaler une erreur pour un déchet",
),
(
"manquant",
"Je souhaite signaler un déchet manquant",
),
(
"bug",
"J'ai trouvé un bug",
),
(
"amelioration",
"Je souhaite proposer une amélioration",
),
(
"autre",
"Autre",
),
],
)
message = forms.CharField(label="Votre message", widget=forms.Textarea)
14 changes: 13 additions & 1 deletion qfdmd/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,13 @@
from django.urls import path
from django.views.generic import RedirectView

from qfdmd.views import CMSPageDetailView, HomeView, SynonymeDetailView, search_view
from qfdmd.views import (
CMSPageDetailView,
ContactFormView,
HomeView,
SynonymeDetailView,
search_view,
)


def get_assistant_script(request):
Expand All @@ -15,6 +21,12 @@ def get_assistant_script(request):
path("dechet/", HomeView.as_view(), name="home"),
path("assistant/recherche", search_view, name="search"),
path("<slug:slug>/", SynonymeDetailView.as_view(), name="synonyme-detail"),
path("assistant/nous-contacter", ContactFormView.as_view(), name="nous-contacter"),
path(
"assistant/nous-contacter/confirmation",
ContactFormView.as_view(),
name="nous-contacter-confirmation",
),
# The URL here needs to be kept as is because it was used in the previous
# Gatsby website. If changed, a redirect need to be created to keep the
# legacy behaviour.
Expand Down
23 changes: 21 additions & 2 deletions qfdmd/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render
from django.views.generic import DetailView, ListView
from django.urls import reverse_lazy
from django.views.generic import DetailView, FormView, ListView

from qfdmd.forms import SearchForm
from core.notion import create_new_row_in_notion_table
from qfdmd.forms import ContactForm, SearchForm
from qfdmd.models import CMSPage, Suggestion, Synonyme

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -39,6 +41,23 @@ def search_view(request) -> HttpResponse:
return render(request, template_name, context=context)


class ContactFormView(FormView):
template_name = "forms/contact.html"
form_class = ContactForm
success_url = reverse_lazy("qfdmd:nous-contacter-confirmation")

def form_valid(self, form):
cleaned_data = form.cleaned_data
submitted_subject = cleaned_data.get("subject")
cleaned_data["subject"] = dict(self.form_class().fields["subject"].choices)[
submitted_subject
]
create_new_row_in_notion_table(
settings.NOTION.get("CONTACT_FORM_DATABASE_ID"), cleaned_data
)
return super().form_valid(form)


class BaseView:
"""Base view that provides templates used on all pages.
TODO: this could be moved to a context processor"""
Expand Down
7 changes: 6 additions & 1 deletion templates/components/sidebar/email/action.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
{% extends "../action.html" %}

{% load dsfr_tags %}

{% block icon %}
{% include "./icon.html" %}
{% endblock icon %}
Expand All @@ -13,7 +15,10 @@
{% endblock modal_title %}

{% block modal_content %}
Formulaire de contact
<turbo-frame id="contact-form"
src="{% url 'qfdmd:nous-contacter' %}"
>
</turbo-frame>
{% endblock modal_content %}

{% block modal_wrapper_for_id %}
Expand Down
22 changes: 22 additions & 0 deletions templates/forms/contact.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<turbo-frame id='contact-form'>
<form
method="post"
action="{% url 'qfdmd:nous-contacter' %}"
>
{% csrf_token %}
{% if request.resolver_match.url_name == 'nous-contacter' %}
{{ form }}
<button class="fr-btn" type="submit">
Envoyer mon message
</button>
{% else %}
<div class="qf-flex qf-flex-row qf-gap-1w qf-items-center">
<span class="fr-icon--lg fr-icon fr-icon-success-fill" aria-hidden="true"></span>

<span>
Votre message a bien été envoyé
</span>
</div>
{% endif %}
</form>
</turbo-frame>

0 comments on commit 856efc2

Please sign in to comment.