Move data parsing logic from the view to separate functions
authorGu1 <gu1@cafai.fr>
Sun, 9 Jun 2013 00:18:21 +0000 (02:18 +0200)
committerGu1 <gu1@cafai.fr>
Sun, 9 Jun 2013 01:37:01 +0000 (03:37 +0200)
fdneligibility/views.py

index 053bbde..1e20705 100644 (file)
@@ -2,6 +2,7 @@
 from django.contrib.formtools.wizard.views import SessionWizardView
 from django.utils.translation import ugettext_lazy as _
 from django.template.response import TemplateResponse
+from django.forms.forms import NON_FIELD_ERRORS
 from forms import EligibilityForm1, EligibilityForm2
 from utils import VerifiedHTTPSConnection, APP_ROOT
 from httplib import HTTPException
@@ -32,28 +33,81 @@ def contact_si_helper(phonen, zipc):
     return json.loads(res.read())
 
 
-class EligibilityWizard(SessionWizardView):
+def clean_rejects(rejects):
+    from bleach import clean # is required by mezzanine anyway..
+    # because rejected plans mixes html and html-escaped content
+    rejects=re.sub(r'&lt;(/?(?:i|b|br))&gt;', r'<\1>', rejects)
+    return clean(rejects, tags=['p', 'b', 'i'], strip=True)
+
+
+plans_upload = {
+    "1Mopt0"    : "256k",
+    "512kopt1"  : "128k",
+    "1Mopt1"    : "256k",
+    "2Mopt1"    : "256k",
+    "8Mopt1"    : "860k",
+    "18Mopt1"   : "860k",
+    "512kopt3"  : "128k",
+    "1Mopt3"    : "256k",
+    "2Mopt3"    : "256k",
+    "3Mopt3"    : u"256k à 512k",
+    "4Mopt3"    : "512k",
+    "5Mopt3"    : "512k",
+    "6Mopt3"    : "512k",
+    "512kopt5"  : "128k",
+    "512REopt5" : "128k",
+    "1Mopt5"    : "256k",
+    "18Mopt5"   : "<=860k",
+    "18Mopt0"   : "1M",
+}
+
+def test_eligibility(phone_number, zip_code, customize_offer=None, sort_offers=None):
+    try:
+        si_res=contact_si_helper(phone_number, zip_code)
+        if 'info_ligne' not in si_res or 'offres' not in si_res:
+            raise RuntimeError(_(u"The eligibility test server returned an error, please try again "\
+                                  "at a later time. If the problem persist, contact us."))
+    except (HTTPException, SSLError), e:
+        raise RuntimeError(_(u"Could not test your eligibility"))
+
+    si_res.setdefault('erreur', 0)
+    for o in si_res['offres']:
+        o['fas_fdn']=Decimal(o['fas'].replace('E TTC', u''))
+        o['abo_fdn']=Decimal(o['abo'].replace('E TTC', u''))
+        del o['fas'], o['abo']
+        plan_id=o['code_offre']
+        del o['code_offre']
+        o['plan_id']=plan_id
+        o['download'] = o['debit']
+        del o['debit']
+        if "opt0" in plan_id:
+            unbundling = _(u"partially unbundled by Nerim")
+        elif "opt1" in plan_id:
+            unbundling = _(u"partially unbundled")
+        elif "opt3" in plan_id:
+            unbundling = _("not unbundled (ACA)")
+        elif "opt5" in plan_id:
+            unbundling = _(u"not unbundled (IP/ADSL)")
+        else:
+            unbundling = _(u"unknown")
+        o['unbundling'] = unbundling
+        try:
+            o['upload'] = plans_upload[o['plan_id']]
+        except KeyError:
+            o['upload'] = u'?'
+
+        if customize_offer:
+            customize_offer(o)
+
+    if sort_offers:
+        si_res['offres']=sort_offers(si_res['offres'])
+
+    si_res['rejets']=clean_rejects(si_res['rejets'])
+
+    return si_res
+
 
-    plans_upload = {
-        "1Mopt0"    : "256k",
-        "512kopt1"  : "128k",
-        "1Mopt1"    : "256k",
-        "2Mopt1"    : "256k",
-        "8Mopt1"    : "860k",
-        "18Mopt1"   : "860k",
-        "512kopt3"  : "128k",
-        "1Mopt3"    : "256k",
-        "2Mopt3"    : "256k",
-        "3Mopt3"    : u"256k à 512k",
-        "4Mopt3"    : "512k",
-        "5Mopt3"    : "512k",
-        "6Mopt3"    : "512k",
-        "512kopt5"  : "128k",
-        "512REopt5" : "128k",
-        "1Mopt5"    : "256k",
-        "18Mopt5"   : "<=860k",
-        "18Mopt0"   : "1M",
-    }
+class EligibilityWizard(SessionWizardView):
 
     @staticmethod
     def _customize_offer_impl(o):
@@ -63,7 +117,8 @@ class EligibilityWizard(SessionWizardView):
 
     customize_offer=_customize_offer_impl
 
-    def sort_offres(self, offres):
+    @staticmethod
+    def _sort_offers_impl(offres):
         unit_table={'k': 1000, 'm': 1000000, 'g': 1000000000}
         def _key(o):
             unit=o['download'][-1].lower()
@@ -71,19 +126,16 @@ class EligibilityWizard(SessionWizardView):
         tmp=sorted(offres, key=lambda o: 0 if o['plan_id'].endswith('opt1') or o['plan_id'].endswith('opt0') else 1)
         return sorted(tmp, key=_key, reverse=True)
 
+    sort_offers=_sort_offers_impl
+
     def get_template_names(self):
         return [TEMPLATES[self.steps.current], "fdneligibility/form.html"]
 
     def get_context_data(self, form, **kwargs):
         context = super(EligibilityWizard, self).get_context_data(form=form, **kwargs)
         if self.steps.current == '1':
-            from bleach import clean # is required by mezzanine anyway..
-
-            rejets=self.storage.extra_data['si_res']['rejets']
-            # because rejets mixes html and html-escaped content
-            rejets=re.sub(r'&lt;(/?(?:i|b|br))&gt;', r'<\1>', rejets)
-            context.update({'unavailable_plans': clean(rejets, tags=['p', 'b', 'i'], strip=True)})
             context.update({
+                'unavailable_plans': self.storage.extra_data['si_res']['rejets'],
                 'phone_number': self.storage.extra_data['phone_number'],
                 'line_info': self.storage.extra_data['si_res']['info_ligne']
             })
@@ -96,49 +148,15 @@ class EligibilityWizard(SessionWizardView):
         return kwargs
 
     def render_next_step(self, form, **kwargs):
-        from django.forms.forms import NON_FIELD_ERRORS
         if self.steps.current == '0': # hackish way to process data and still control the form displayed next
             phone_number = form.cleaned_data.get('phone_number')
             zip_code     = form.cleaned_data.get('zip_code')
             try:
-                si_res=contact_si_helper(phone_number, zip_code)
-                if 'info_ligne' not in si_res or 'offres' not in si_res:
-                    form._errors[NON_FIELD_ERRORS] = form.error_class([_(u"The eligibility test server returned an error, please try again "
-                                                                          "at a later time. If the problem persist, contact us.")])
-                    return self.render(form)
-                si_res.setdefault('erreur', 0)
-                for o in si_res['offres']:
-                    o['fas_fdn']=Decimal(o['fas'].replace('E TTC', u''))
-                    o['abo_fdn']=Decimal(o['abo'].replace('E TTC', u''))
-                    del o['fas'], o['abo']
-                    plan_id=o['code_offre']
-                    del o['code_offre']
-                    o['plan_id']=plan_id
-                    o['download'] = o['debit']
-                    del o['debit']
-                    if "opt0" in plan_id:
-                        unbundling = _(u"partially unbundled by Nerim")
-                    elif "opt1" in plan_id:
-                        unbundling = _(u"partially unbundled")
-                    elif "opt3" in plan_id:
-                        unbundling = _("not unbundled (ACA)")
-                    elif "opt5" in plan_id:
-                        unbundling = _(u"not unbundled (IP/ADSL)")
-                    else:
-                        unbundling = _(u"unknown")
-                    o['unbundling'] = unbundling
-                    try:
-                        o['upload'] = self.plans_upload[o['plan_id']]
-                    except KeyError:
-                        o['upload'] = u'?'
-
-                    self.customize_offer(o)
-
-                si_res['offres']=self.sort_offres(si_res['offres'])
-                self.storage.extra_data={'si_res': si_res, 'phone_number': phone_number}
-            except (HTTPException, SSLError), e:
-                form._errors[NON_FIELD_ERRORS] = form.error_class([_(u"Could not test your eligibility")])
+                si_res=test_eligibility(phone_number, zip_code, self.customize_offer, self.sort_offers)
+            except RuntimeError as e:
+                form._errors[NON_FIELD_ERRORS] = form.error_class([e.args[0]])
                 return self.render(form)
+            self.storage.extra_data={'si_res': si_res, 'phone_number': phone_number}
 
         return super(EligibilityWizard, self).render_next_step(form, **kwargs)