From 6bed0dcaef64d5903619ac85b8f49a2300ba9006 Mon Sep 17 00:00:00 2001 From: Igor Santos Date: Wed, 27 Sep 2023 11:32:52 -0300 Subject: [PATCH] fix(pressure): add render to form errors --- app/contrib/actions/pressure/forms.py | 65 +++++++++-------- .../pressure/static/pressure/js/pressure.js | 73 +++++++++++-------- .../templates/pressure/pressure_plugin.html | 1 + app/contrib/actions/pressure/views.py | 16 ++-- 4 files changed, 86 insertions(+), 69 deletions(-) diff --git a/app/contrib/actions/pressure/forms.py b/app/contrib/actions/pressure/forms.py index f6d2fc81..495f6482 100644 --- a/app/contrib/actions/pressure/forms.py +++ b/app/contrib/actions/pressure/forms.py @@ -33,38 +33,41 @@ class Meta(StyledBaseForm.Meta): readonly_fields = ["email_subject", "email_body"] def submit(self): - activist = { - "email": self.cleaned_data["email_address"], - "name": self.cleaned_data["name"], - "phone": self.cleaned_data["phone_number"], - } - - input = { - "email_subject": self.cleaned_data["email_subject"], - "email_body": self.cleaned_data["email_body"], - "form_data": json.dumps(self.cleaned_data), - "token": jwt.encode({}, settings.BONDE_ACTION_SECRET_KEY), - } + try: + activist = { + "email": self.cleaned_data["email_address"], + "name": self.cleaned_data["name"], + "phone": self.cleaned_data["phone_number"], + } - query = """ - mutation Pressure($activist: ActivistInput!, $input: EmailPressureInput, $widget_id: Int!) { - create_email_pressure( - activist: $activist, - widget_id: $widget_id, - input: $input - ) { - data + input = { + "email_subject": self.cleaned_data["email_subject"], + "email_body": self.cleaned_data["email_body"], + "form_data": json.dumps(self.cleaned_data), + "token": jwt.encode({}, settings.BONDE_ACTION_SECRET_KEY), } + + query = """ + mutation Pressure($activist: ActivistInput!, $input: EmailPressureInput, $widget_id: Int!) { + create_email_pressure( + activist: $activist, + widget_id: $widget_id, + input: $input + ) { + data + } + } + """ + variables = { + "activist": activist, + "input": input, + "widget_id": self.cleaned_data["reference_id"], } - """ - variables = { - "activist": activist, - "input": input, - "widget_id": self.cleaned_data["reference_id"], - } - resp = requests.post(settings.BONDE_ACTION_API_URL, json={"query": query, "variables": variables}) - if resp.status_code == 200: - print(resp.json()) - else: - raise Exception("Query failed to run by returning code of {}. {}".format(resp.status_code, query)) + resp = requests.post(settings.BONDE_ACTION_API_URL, json={"query": query, "variables": variables}) + if resp.status_code == 200: + print(resp.json()) + else: + raise Exception("Query failed to run by returning code of {}. {}".format(resp.status_code, query)) + except requests.ConnectionError: + raise Exception("ConnectionError") diff --git a/app/contrib/actions/pressure/static/pressure/js/pressure.js b/app/contrib/actions/pressure/static/pressure/js/pressure.js index 866a9d62..e5152a36 100644 --- a/app/contrib/actions/pressure/static/pressure/js/pressure.js +++ b/app/contrib/actions/pressure/static/pressure/js/pressure.js @@ -3,42 +3,51 @@ $(function () { $(".pressure-plugin form").on("submit", function (evt) { - const $form = $(this); - - function showTooltip() { - const tooltip = $("#copyToClipboardTooltip"); - tooltip.toggleClass("tooltip-open hover:before:block hover:after:block"); - - // hide after 3 seconds - window.setTimeout(function () { - tooltip.removeClass("tooltip-open hover:before:block hover:after:block"); - }, 2000); - } - - function handleResponse(data) { - if (data.success) { - $("#pressureWrapper").empty(); - $("#pressureWrapper").html(data.html); - - $("#copyToClipboard").on("click", function () { - const textToCopy = window.location.href; - - navigator.clipboard - .writeText(textToCopy) - .then(showTooltip) - .catch(() => console.error("Erro ao copiar link, tente novamente.")); - }); + const $form = $(this); + + function showTooltip() { + const tooltip = $("#copyToClipboardTooltip"); + tooltip.toggleClass("tooltip-open hover:before:block hover:after:block"); + + // hide after 3 seconds + window.setTimeout(function () { + tooltip.removeClass("tooltip-open hover:before:block hover:after:block"); + }, 2000); + } + + function handleResponse({ status, responseJSON }) { + if (status === 200 && responseJSON.success) { + $("#pressureWrapper").empty(); + $("#pressureWrapper").html(data.html); + + $("#copyToClipboard").on("click", function () { + const textToCopy = window.location.href; + + navigator.clipboard + .writeText(textToCopy) + .then(showTooltip) + .catch(() => console.error("Erro ao copiar link, tente novamente.")); + }); window.gtag("event", "form_submit_success", { form_id: $form.attr("id") }); } else { $form.find('.errorlist').empty(); - $.each(data, function (key, value) { - const $field = $form.find("input[name=" + key + "]").first(); - $field.parents(".form-control").find(".errorlist").html( - $.each(value, function (item) { - return "
  • " + item + "
  • " - }) - ); + $.each(responseJSON.errors, function (key, value) { + if (key === '__all__') { + const $errorlist = $form.find("[type='submit'] + .errorlist"); + $errorlist.html( + $.each(value, function (item) { + return "
  • " + item + "
  • " + }) + ); + } else { + const $field = $form.find("input[name=" + key + "]").first(); + $field.parents(".form-control").find(".errorlist").html( + $.each(value, function (item) { + return "
  • " + item + "
  • " + }) + ); + } }); window.gtag("event", "form_submit_failed", { form_id: $form.attr("id") }); } diff --git a/app/contrib/actions/pressure/templates/pressure/pressure_plugin.html b/app/contrib/actions/pressure/templates/pressure/pressure_plugin.html index fc912570..3654d7fc 100644 --- a/app/contrib/actions/pressure/templates/pressure/pressure_plugin.html +++ b/app/contrib/actions/pressure/templates/pressure/pressure_plugin.html @@ -39,6 +39,7 @@

    {{settings.title}}

    {% for hidden_field in form.hidden_fields %}{{hidden_field}}{% endfor %}
    +

    Ao inserir seus dados, você concorda em ter seus dados compartilhados com os organizadores dessa página e aceita receber emails de atualização, conforme descrito na política de privacidade. Você pode cancelar o recebimento desses e-mails a qualquer momento.

    diff --git a/app/contrib/actions/pressure/views.py b/app/contrib/actions/pressure/views.py index 7b63b9e3..64071fef 100644 --- a/app/contrib/actions/pressure/views.py +++ b/app/contrib/actions/pressure/views.py @@ -29,12 +29,16 @@ def form_valid(self, form): response = super().form_valid(form) if self.request.is_ajax(): - form.submit() - data = { - 'success': True, - 'html': render(self.request, 'pressure/pressure_success.html', {"form_data": form.cleaned_data}).content.decode('utf-8') - } - return self.render_to_json_response(data) + try: + form.submit() + data = { + 'success': True, + 'html': render(self.request, 'pressure/pressure_success.html', {"form_data": form.cleaned_data}).content.decode('utf-8') + } + return self.render_to_json_response(data) + except Exception as err: + form.add_error(None, err) + return self.render_to_json_response({ 'success': False, 'errors': form.errors }, status=500) else: return response