Permalink
Browse files

Bug 799283: Enable newsletter form for all locales.

Add country and language fields to form.
Convert form to macro.
Add source_url to submission.
Make country and language fields optional.
Add country to apps form. Ensure empty values aren't sent to basket.
Fix bug 799283.
  • Loading branch information...
1 parent 02c535f commit 294152a38b3fa0baba8ffdb9694586559e9dbfe4 @pmac pmac committed Oct 24, 2012
@@ -1,4 +1,5 @@
{% extends "firefox/mobile/sms-base.html" %}
+{% from "macros.html" import email_newsletter_form with context %}
{% block content %}
@@ -27,65 +28,7 @@ <h1 class="large">{{_('Your link has been sent!')}}</h1>
</div>
</div>
-
- {% if LANG.startswith('en') %}
- {% if not request.newsletter_success %}
- {% if request.newsletter_form.errors %}
- <div id="footer-email-errors">
- {{ request.newsletter_form.non_field_errors()|safe }}
-
- <ul class="errorlist">
- {% if request.newsletter_form.email.errors %}
- <li>{{_('Please enter a valid email address')}}</li>
- {% endif %}
-
- {% if request.newsletter_form.newsletter.errors %}
- <li>{{ request.newsletter_form.newsletter.errors }}</li>
- {% endif %}
-
- {% if request.newsletter_form.privacy.errors %}
- <li>{{_('You must agree to the privacy policy')}}</li>
- {% endif %}
- </ul>
- </div>
- {% endif %}
-
- <form class="{% if request.newsletter_form.errors %} has-errors{% endif%}"
- id="footer-email-form" action="#footer-email-form" method="post"
- onsubmit="dcsMultiTrack('DCS.dcsuri','/signmeup.button','WT.ti','Sign%20Me%20Up','WT.dl','26');">
- <input type="hidden" name="newsletter-footer" value="Y" />
- <input type="hidden" name="newsletter"
- value="{% block email_form_newsletter %}mozilla-and-you{% endblock %}" />
-
- <h3>{% block email_form_title %}{{_('Get Firefox news')}}{% endblock %}</h3>
-
- <div class="form-contents">
- <div class="field field-email {% if request.newsletter_form.email.errors %}field-error{% endif %}">
- {{ field_with_attrs(request.newsletter_form.email, placeholder=_('YOUR EMAIL HERE'))|safe }}
- </div>
-
- <div id="form-details">
- <div class="field field-format">
- {{ request.newsletter_form.fmt|safe }}
- </div>
- <div class="field field-privacy {% if request.newsletter_form.privacy.errors%}field-error{% endif %}">
- {{ request.newsletter_form.privacy|safe }}
- </div>
- </div>
- </div>
-
- <div class="form-submit">
- <input type="submit" id="footer_email_submit" value="Sign me up »" class="button">
- <p class="form-details"><small>{{_('We will only send you Mozilla-related information.')}}</small></p>
- </div>
-
- </form>
- {% else %}
- <div id="footer-email-form" class="thank billboard">
- <h3>{{_('Thank you for signing up!')}}</h3>
- </div>
- {% endif %}
- {% endif %}
+ {{ email_newsletter_form() }}
</div>
{{ super() }}
@@ -102,11 +102,9 @@ <h1 id="whatsnew-header">{{ _('Hooray! Your Firefox is up to date.') }}</h1>
{% endblock %}
{% block email_form %}
- {% if LANG.startswith('en') %}
- <div id="email-form-wrapper" class="billboard">
- {{ super() }}
- </div>
- {% endif %}
+ <div id="email-form-wrapper" class="billboard">
+ {{ super() }}
+ </div>
{% endblock%}
@@ -1,4 +1,5 @@
-{% extends "base-resp.html" %}:
+{% extends "base-resp.html" %}
+{% from "macros.html" import email_newsletter_form with context %}
{% block page_title_prefix %}{% endblock %}
{% block page_title %}Firefox Marketplace{% endblock %}
@@ -170,8 +171,11 @@
{% endblock %}
-{% block email_form_title %}{{_('Sign up for more news about the Firefox Marketplace.')}}{% endblock %}
-{% block email_form_newsletter %}app-dev{% endblock %}
+{% block email_form %}
+ {{ email_newsletter_form('app-dev',
+ _('Sign up for more news about the Firefox Marketplace.'),
+ include_language=False) }}
+{% endblock %}
{% block js %}
<!--[if gte IE 9]><!-->
View
@@ -1,6 +1,9 @@
# coding: utf-8
+import re
+from operator import itemgetter
from django import forms
+from django.conf import settings
from django.forms import widgets
from django.utils.safestring import mark_safe
@@ -9,7 +12,35 @@
from product_details import product_details
from .email_contribute import INTEREST_CHOICES
+
+
FORMATS = (('H', 'HTML'), ('T', 'Text'))
+LANGS = settings.NEWSLETTER_LANGUAGES
+LANGS_TO_STRIP = ['en-US', 'es']
+PARENTHETIC_RE = re.compile(r' \([^)]+\)$')
+
+
+def strip_parenthetical(lang_name):
+ """
+ Remove the parenthetical from the end of the language name string.
+ """
+ return PARENTHETIC_RE.sub('', lang_name, 1)
+
+
+def get_lang_choices():
+ """
+ Return a list of choices for language localized for the given locale.
+ """
+ lang_choices = []
+ for lang in LANGS:
+ try:
+ lang_name = product_details.languages[lang]['native']
+ except KeyError:
+ continue
+ if lang in LANGS_TO_STRIP:
+ lang_name = strip_parenthetical(lang_name)
+ lang_choices.append([lang, lang_name])
+ return sorted(lang_choices, key=itemgetter(1))
class SideRadios(widgets.RadioFieldRenderer):
@@ -29,7 +60,8 @@ def render(self, name, value, attrs=None):
attrs['required'] = 'true'
input_txt = super(PrivacyWidget, self).render(name, value, attrs)
- policy_txt = _(u'I’m okay with you handling this info as you explain in your <a href="%s">Privacy Policy</a>')
+ policy_txt = _(u'I’m okay with you handling this info as you explain '
+ u'in your <a href="%s">Privacy Policy</a>')
return mark_safe(
'<label for="%s" class="privacy-check-label">'
'%s '
@@ -54,20 +86,25 @@ class NewsletterForm(forms.Form):
choices=FORMATS,
initial='H')
privacy = forms.BooleanField(widget=PrivacyWidget)
+ source_url = forms.URLField(verify_exists=False, required=False)
-
-class NewsletterCountryForm(NewsletterForm):
def __init__(self, locale, *args, **kwargs):
regions = product_details.get_regions(locale)
regions = sorted(regions.iteritems(), key=lambda x: x[1])
- locale = locale.lower()
+ lang_choices = get_lang_choices()
+ lang_initial = locale if locale in LANGS else 'en-US'
- if locale.find('-') != -1:
- locale = locale.split('-')[1]
+ ccode = locale.lower()
+ if '-' in ccode:
+ ccode = ccode.split('-')[1]
- super(NewsletterCountryForm, self).__init__(*args, **kwargs)
+ super(NewsletterForm, self).__init__(*args, **kwargs)
self.fields['country'] = forms.ChoiceField(choices=regions,
- initial=locale)
+ initial=ccode,
+ required=False)
+ self.fields['lang'] = forms.ChoiceField(choices=lang_choices,
+ initial=lang_initial,
+ required=False)
class ContributeForm(forms.Form):
View
@@ -41,20 +41,28 @@ class NewsletterMiddleware(object):
"""Processes newsletter subscriptions"""
def process_request(self, request):
success = False
- form = NewsletterForm(request.POST or None)
+ form = NewsletterForm(request.locale, request.POST or None)
is_footer_form = (request.method == 'POST' and
'newsletter-footer' in request.POST)
if is_footer_form:
if form.is_valid():
data = form.cleaned_data
+ kwargs = {
+ 'format': data['fmt'],
+ }
+ # add optional data
+ kwargs.update(dict((k, data[k]) for k in ['country',
+ 'lang',
+ 'source_url']
+ if data[k]))
try:
basket.subscribe(data['email'], data['newsletter'],
- format=data['fmt'])
+ **kwargs)
success = True
except basket.BasketException:
- msg = _lazy("We are sorry, but there was a problem with our system. "
- "Please try again later!")
+ msg = _lazy("We are sorry, but there was a problem "
+ "with our system. Please try again later!")
form.errors['__all__'] = form.error_class([msg])
request.newsletter_form = form
@@ -6,7 +6,7 @@
import basket
import jingo
-from mock import Mock, patch
+from mock import patch
from nose.tools import assert_false, assert_not_equal, eq_, ok_
from product_details import product_details
from pyquery import PyQuery as pq
@@ -254,19 +254,44 @@ def test_get_form(self):
assert_false(doc('#footer-email-errors'))
ok_(doc('form#footer-email-form'))
- @patch.object(basket, 'subscribe', Mock())
- def test_post_correct_form(self):
+ @patch.object(basket, 'subscribe')
+ def test_post_correct_form(self, sub_mock):
data = {
'newsletter-footer': 'Y',
'newsletter': 'mozilla-and-you',
'email': 'foo@bar.com',
+ 'country': 'us',
+ 'lang': 'en-US',
'fmt': 'H',
'privacy': 'Y',
+ 'source_url': 'http://allizom.com/en-US/base/',
}
response = self.client.post('/en-US/base/', data)
doc = pq(response.content)
assert_false(doc('form#footer-email-form'))
ok_(doc('div#footer-email-form.thank'))
+ sub_mock.assert_called_with('foo@bar.com', 'mozilla-and-you',
+ format='H', country='us', lang='en-US',
+ source_url='http://allizom.com/en-US/base/')
+
+ @patch.object(basket, 'subscribe')
+ def test_post_form_country_lang_not_required(self, sub_mock):
+ """
+ Form should successfully post without country, lang, or src url.
+ """
+ data = {
+ 'newsletter-footer': 'Y',
+ 'newsletter': 'mozilla-and-you',
+ 'email': 'foo@bar.com',
+ 'fmt': 'H',
+ 'privacy': 'Y',
+ }
+ response = self.client.post('/en-US/base/', data)
+ doc = pq(response.content)
+ assert_false(doc('form#footer-email-form'))
+ ok_(doc('div#footer-email-form.thank'))
+ sub_mock.assert_called_with('foo@bar.com', 'mozilla-and-you',
+ format='H')
def test_post_wrong_form(self):
response = self.client.post('/en-US/base/', {'newsletter-footer': 'Y'})
@@ -0,0 +1,55 @@
+from mozorg.tests import TestCase
+
+from django.test.client import Client
+
+from funfactory.urlresolvers import reverse
+from nose.tools import eq_
+from pyquery import PyQuery as pq
+
+
+class TestNewsletter(TestCase):
+ def setUp(self):
+ self.view_name = 'firefox.fx'
+ self.client = Client()
+
+ def test_country_selected(self):
+ """
+ The correct country for the locale should be initially selected.
+ """
+ with self.activate('en-US'):
+ resp = self.client.get(reverse(self.view_name))
+ doc = pq(resp.content)
+ eq_(doc('#id_country option[selected="selected"]').val(), 'us')
+
+ with self.activate('fr'):
+ resp = self.client.get(reverse(self.view_name))
+ doc = pq(resp.content)
+ eq_(doc('#id_country option[selected="selected"]').val(), 'fr')
+
+ with self.activate('pt-BR'):
+ resp = self.client.get(reverse(self.view_name))
+ doc = pq(resp.content)
+ eq_(doc('#id_country option[selected="selected"]').val(), 'br')
+
+ def test_language_selected(self):
+ """
+ The correct language for the locale should be initially selected or
+ en-US if it's not an option.
+ """
+ with self.activate('fr'):
+ resp = self.client.get(reverse(self.view_name))
+
+ doc = pq(resp.content)
+ eq_(doc('#id_lang option[selected="selected"]').val(), 'fr')
+
+ with self.activate('pt-BR'):
+ resp = self.client.get(reverse(self.view_name))
+
+ doc = pq(resp.content)
+ eq_(doc('#id_lang option[selected="selected"]').val(), 'pt-BR')
+
+ with self.activate('ak'):
+ resp = self.client.get(reverse(self.view_name))
+
+ doc = pq(resp.content)
+ eq_(doc('#id_lang option[selected="selected"]').val(), 'en-US')
View
@@ -4,7 +4,7 @@
import l10n_utils
from mozorg import email_contribute
-from mozorg.forms import ContributeForm, NewsletterCountryForm
+from mozorg.forms import ContributeForm, NewsletterForm
@csrf_exempt
@@ -35,9 +35,9 @@ def contribute(request, template, return_to_form):
form = ContributeForm()
if has_newsletter_form:
- newsletter_form = NewsletterCountryForm(locale,
- request.POST,
- prefix='newsletter')
+ newsletter_form = NewsletterForm(locale,
+ request.POST,
+ prefix='newsletter')
if newsletter_form.is_valid():
data = newsletter_form.cleaned_data
@@ -54,7 +54,7 @@ def contribute(request, template, return_to_form):
)
newsletter_form.errors['__all__'] = msg
else:
- newsletter_form = NewsletterCountryForm(locale, prefix='newsletter')
+ newsletter_form = NewsletterForm(locale, prefix='newsletter')
return l10n_utils.render(request,
template,
Oops, something went wrong.

0 comments on commit 294152a

Please sign in to comment.