Skip to content

Commit

Permalink
fix(pressure): add render to form errors
Browse files Browse the repository at this point in the history
  • Loading branch information
igr-santos committed Sep 27, 2023
1 parent b2b60ff commit 6bed0dc
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 69 deletions.
65 changes: 34 additions & 31 deletions app/contrib/actions/pressure/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
73 changes: 41 additions & 32 deletions app/contrib/actions/pressure/static/pressure/js/pressure.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 "<li>" + item + "</li>"
})
);
$.each(responseJSON.errors, function (key, value) {
if (key === '__all__') {
const $errorlist = $form.find("[type='submit'] + .errorlist");
$errorlist.html(
$.each(value, function (item) {
return "<li>" + item + "</li>"
})
);
} else {
const $field = $form.find("input[name=" + key + "]").first();
$field.parents(".form-control").find(".errorlist").html(
$.each(value, function (item) {
return "<li>" + item + "</li>"
})
);
}
});
window.gtag("event", "form_submit_failed", { form_id: $form.attr("id") });
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ <h3 class="px-4 pt-4 text-lg font-bold text-center">{{settings.title}}</h3>
{% for hidden_field in form.hidden_fields %}{{hidden_field}}{% endfor %}
<div class="flex flex-col gap-4 px-6 pt-4 pb-6">
<button type="submit" class="w-full btn">{{settings.button}}</button>
<ul class="errorlist"></ul>
<p class="text-xs">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.</p>
Expand Down
16 changes: 10 additions & 6 deletions app/contrib/actions/pressure/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit 6bed0dc

Please sign in to comment.