Commits

Doug Latornell committed 2fe3ca7

Add updating of populaire rider list spreadsheet on Google Drive.

Comments (0)

Files changed (5)

 pyramid.debug_routematch = false
 pyramid.default_locale_name = en
 pyramid.includes =
+    pyramid_celery
     pyramid_debugtoolbar
     pyramid_deform
     pyramid_mailer
 
 timezone = Canada/Pacific
 
+# celery configuration
+BROKER_URL = sqla+sqlite:///celerydb.sqlite
+
 [server:main]
 use = egg:waitress#main
 host = 0.0.0.0

randopony/tests/test_site.py

         request = testing.DummyRequest()
         request.matchdict['short_name'] = 'VicPop'
         views = self._make_one(request)
-        with patch.object(pop_module, 'datetime') as mock_datetime, \
-             patch.object(pop_module, 'render') as mock_render:
+        datetime_patch = patch.object(pop_module, 'datetime')
+        render_patch = patch.object(pop_module, 'render')
+        with datetime_patch as mock_datetime, render_patch as mock_render:
             mock_datetime.today.return_value = datetime(2011, 4, 7, 15, 52)
             views._moved_on_page()
         tmpl_name = mock_render.call_args[0][0]
         self.config = testing.setUp(
             settings={
                 'mako.directories': 'randopony:templates',
+                'google_docs.username': 'randopony',
+                'google_docs.password': 'sEcReT',
             })
         self.config.include('pyramid_mailer.testing')
         self.config.add_route('populaire', '/populaires/{short_name}')
             Populaire,
             PopulaireRider,
             )
+        from ..views.site import populaire as pop_module
         populaire = Populaire(
             event_name='Victoria Populaire',
             short_name='VicPop',
         request = testing.DummyRequest()
         request.matchdict['short_name'] = 'VicPop'
         entry = self._make_one(request)
-        url = entry.register_success({
-            'email': 'fred@example.com',
-            'first_name': 'Fred',
-            'last_name': 'Dickson',
-            'comment': 'Sunshine Man',
-            'distance': 100,
-            'populaire': populaire_id,
-            })
+        with patch.object(pop_module, 'update_google_spreadsheet') as mock_task:
+            url = entry.register_success({
+                'email': 'fred@example.com',
+                'first_name': 'Fred',
+                'last_name': 'Dickson',
+                'comment': 'Sunshine Man',
+                'distance': 100,
+                'populaire': populaire_id,
+                })
         rider = DBSession.query(PopulaireRider).first()
         self.assertEqual(rider.email, 'fred@example.com')
         self.assertEqual(rider.full_name, 'Fred "Sunshine Man" Dickson')
             Populaire,
             PopulaireRider,
             )
+        from ..views.site import populaire as pop_module
         populaire = Populaire(
             event_name="New Year's Populaire",
             short_name='NewYearsPop',
         request = testing.DummyRequest()
         request.matchdict['short_name'] = 'NewYearsPop'
         entry = self._make_one(request)
-        entry.register_success({
-            'email': 'fred@example.com',
-            'first_name': 'Fred',
-            'last_name': 'Dickson',
-            'comment': 'Sunshine Man',
-            'populaire': populaire_id,
-            })
+        with patch.object(pop_module, 'update_google_spreadsheet') as mock_task:
+            entry.register_success({
+                'email': 'fred@example.com',
+                'first_name': 'Fred',
+                'last_name': 'Dickson',
+                'comment': 'Sunshine Man',
+                'populaire': populaire_id,
+                })
         rider = DBSession.query(PopulaireRider).first()
         self.assertEqual(rider.distance, 60)
 
         """successful entry sends emails to rider and organizer
         """
         from ..models import Populaire
+        from ..views.site import populaire as pop_module
         populaire = Populaire(
             event_name="New Year's Populaire",
             short_name='NewYearsPop',
         request.matchdict['short_name'] = 'NewYearsPop'
         mailer = get_mailer(request)
         entry = self._make_one(request)
-        entry.register_success({
-            'email': 'fred@example.com',
-            'first_name': 'Fred',
-            'last_name': 'Dickson',
-            'comment': 'Sunshine Man',
-            })
+        with patch.object(pop_module, 'update_google_spreadsheet') as mock_task:
+            entry.register_success({
+                'email': 'fred@example.com',
+                'first_name': 'Fred',
+                'last_name': 'Dickson',
+                'comment': 'Sunshine Man',
+                })
         self.assertEqual(len(mailer.queue), 2)
 
     def test_rider_email_message(self):
             registration_end=datetime(2011, 3, 24, 12, 0),
             entry_form_url='http://www.randonneurs.bc.ca/VicPop/'
                            'VicPop11_registration.pdf',
-            google_doc_id=
-                'spreadsheet:0AtBTJntkFrPQdFJDN3lvRmVOQW5RXzRZbzRTRFJLYnc',
+            google_doc_id='spreadsheet:'
+                '0AtBTJntkFrPQdFJDN3lvRmVOQW5RXzRZbzRTRFJLYnc',
             )
         rider = PopulaireRider(
             email='fred@example.com',
             registration_end=datetime(2011, 3, 24, 12, 0),
             entry_form_url='http://www.randonneurs.bc.ca/VicPop/'
                            'VicPop11_registration.pdf',
-            google_doc_id=
-                'spreadsheet:0AtBTJntkFrPQdFJDN3lvRmVOQW5RXzRZbzRTRFJLYnc',
+            google_doc_id='spreadsheet:'
+                '0AtBTJntkFrPQdFJDN3lvRmVOQW5RXzRZbzRTRFJLYnc',
             )
         rider = PopulaireRider(
             email='fred@example.com',
         self.assertEqual(
             msg.recipients, ['mjansson@example.com', 'mcroy@example.com'])
 
+    def test_register_success_queues_update_google_spreadsheet_task(self):
+        """successful registration queues task to update rider list spreadsheet
+        """
+        from ..models import Populaire
+        from ..views.site import populaire as pop_module
+        populaire = Populaire(
+            event_name="New Year's Populaire",
+            short_name='NewYearsPop',
+            distance='60 km',
+            date_time=datetime(2013, 1, 1, 10, 0),
+            start_locn='Kelseys Family Restaurant, 325 Burnside Rd W, Victoria',
+            organizer_email='mcroy@example.com',
+            registration_end=datetime(2012, 12, 31, 17, 0),
+            entry_form_url='http://www.randonneurs.bc.ca/organize/eventform.pdf',
+            google_doc_id='spreadsheet:'
+                '0AtBTJntkFrPQdFJDN3lvRmVOQW5RXzRZbzRTRFJLYnc',
+            )
+        with transaction.manager:
+            DBSession.add(populaire)
+            populaire_organizer_email = populaire.organizer_email
+        request = testing.DummyRequest()
+        request.matchdict['short_name'] = 'NewYearsPop'
+        mailer = get_mailer(request)
+        entry = self._make_one(request)
+        with patch.object(pop_module, 'update_google_spreadsheet') as mock_task:
+            entry.register_success({
+                'email': 'fred@example.com',
+                'first_name': 'Fred',
+                'last_name': 'Dickson',
+                'comment': 'Sunshine Man',
+                })
+        mock_task.delay.assert_called_once()
+
     def test_failure(self):
         """populaire entry form validation failure returns expected tmpl_vars
         """

randopony/views/admin/populaire.py

         request.session.flash('error')
         request.session.flash('Rider list spreadsheet already created')
         return HTTPFound(redirect_url)
-    username = request.registry.settings['google_docs.username']
-    password = request.registry.settings['google_docs.password']
-    client = google_docs_login(DocsClient, username, password)
+    client = google_docs_login(
+        DocsClient,
+        request.registry.settings['google_docs.username'],
+        request.registry.settings['google_docs.password'])
     template = get_rider_list_template('Populaire Rider List Template', client)
     created_doc = client.copy_resource(template, str(populaire))
     share_rider_list_publicly(created_doc, client)

randopony/views/site/populaire.py

     timedelta,
     )
 import logging
+from celery.task import task
 from deform import Button
+from gdata.spreadsheet.service import SpreadsheetsService
 from pyramid_deform import FormView
 from pyramid.httpexceptions import (
     HTTPFound,
 import pytz
 import transaction
 from .core import SiteViews
+from ..admin.core import google_docs_login
 from ...models import (
     Brevet,
     EmailAddress,
                     )
                 populaire.riders.append(rider)
                 DBSession.add(rider)
-                self.request.session.flash('success')
-                self.request.session.flash(rider.email)
+                update_google_spreadsheet.delay(
+                    [rider for rider in populaire.riders],
+                    populaire.google_doc_id.split(':')[1],
+                    self.request.registry.settings['google_docs.username'],
+                    self.request.registry.settings['google_docs.password'])
                 message = self._rider_message(populaire, rider)
                 mailer.send_to_queue(message)
                 message = self._organizer_message(populaire, rider)
                 mailer.send_to_queue(message)
+                self.request.session.flash('success')
+                self.request.session.flash(rider.email)
         return HTTPFound(self._redirect_url(pop_short_name))
 
     def failure(self, e):
                     'admin_email': admin_email,
                 }))
         return message
+
+
+@task(ignore_result=True)
+def update_google_spreadsheet(riders, doc_key, username, password):
+    client = google_docs_login(SpreadsheetsService, username, password)
+    spreadsheet_list = client.GetListFeed(doc_key)
+    spreadsheet_rows = len(spreadsheet_list.entry)
+    # Update the rows already in the spreadsheet
+    for row, rider in enumerate(riders[:spreadsheet_rows]):
+        rider_number = row + 1
+        new_row_data = _make_spreadsheet_row_dict(rider_number, rider)
+        client.UpdateRow(spreadsheet_list.entry[row], new_row_data)
+    # Add remaining rows
+    for row, rider in enumerate(riders[spreadsheet_rows:]):
+        rider_number = spreadsheet_rows + row + 1
+        row_data = _make_spreadsheet_row_dict(rider_number, rider)
+        client.InsertRow(row_data, doc_key)
+
+
+def _make_spreadsheet_row_dict(rider_number, rider):
+        row_data = {
+            'ridernumber': str(rider_number),
+            'lastname': rider.last_name,
+            'firstname': rider.first_name,
+            'distance': str(rider.distance),
+        }
+        return row_data
     'deform',
     'gdata',
     'pyramid',
+    'pyramid_celery',
     'pyramid_debugtoolbar',
     'pyramid_deform',
     'pyramid_mailer',