Ejemplo n.º 1
0
class DashboardHandler(BaseHandler):

    businessDao = DaoFactory.create_rw_businessDao()
    eventDao = DaoFactory.create_rw_eventDao()
    childeventDao = DaoFactory.create_rw_childeventDao()
    playgroundDao = DaoFactory.create_rw_playgroundDao()
    trainingcentreDao = DaoFactory.create_rw_trainingCentreDao()
    matchDao = DaoFactory.create_rw_matchDao()
    teamDao = DaoFactory.create_rw_teamDao()
    playerDao = DaoFactory.create_rw_playerDao()

    @user_required
    def get(self, business_id=None):
        params = {}
        params['title'] = 'Dashboard'
        params['owner_business'] = self.businessDao.query_by_owner(
            self.user_info)
        params['owner_playgrounds'] = self.playgroundDao.query_by_owner(
            self.user_info)
        params['owner_events'] = self.eventDao.query_by_owner(self.user_info)
        params['owner_childevents'] = self.childeventDao.query_by_owner(
            self.user_info)
        params[
            'owner_trainingcentres'] = self.trainingcentreDao.query_by_owner(
                self.user_info)
        params['owner_matches'] = self.matchDao.query_by_owner(self.user_info)
        params['owner_teams'] = self.teamDao.query_by_owner(self.user_info)
        params['owner_players'] = self.playerDao.query_by_owner(self.user_info)
        return self.render_template('/cms/dashboard.html', **params)
Ejemplo n.º 2
0
class ManageBulkDataHandler(blobstore_handlers.BlobstoreUploadHandler,
                            BaseHandler):

    bulkdataDao = DaoFactory.create_rw_bulkdataDao()
    businessDao = DaoFactory.create_rw_businessDao()
    mediaDao = DaoFactory.create_rw_mediaDao()

    @user_required
    def get(self, masterdata_id=None):
        params = {}

        upload_url = self.uri_for('create-bulk-data')
        continue_url = self.request.get('continue').encode('ascii', 'ignore')
        status = self.request.get('status')
        pg_status = status if status != '' else None
        params['title'] = 'Create Bulk Data'
        params['weekdays'] = constants.DAYS_LIST

        if masterdata_id is not None and len(masterdata_id) > 1:
            masterdata = self.playgroundDao.get_record(masterdata_id)
            params['title'] = 'Update - ' + str(masterdata.name)
            params['continue_url'] = continue_url
            if pg_status is not None:
                logger.info('current status: %s' % pg_status)
                key = self.playgroundDao.status_change(masterdata,
                                                       self.user_info)
                if key is not None:
                    updated_pg = self.playgroundDao.get_record(long(key.id()))
                    logger.info('updated status : %s' % updated_pg.status)
                    if pg_status == str(updated_pg.status):
                        logger.info('masterdata status could not be changed.')
                        message = ('masterdata status could not be changed.')
                        self.add_message(message, 'error')
                    else:
                        logger.info('masterdata status succesfully changed.')
                        message = ('masterdata status succesfully changed.')
                        self.add_message(message, 'success')
                    return self.redirect(continue_url)
            else:
                upload_url = self.uri_for('edit-masterdata',
                                          masterdata_id=masterdata_id)
                all_media = self.mediaDao.get_all_media(
                    masterdata.key, constants.PLAYGROUND)
                current_media = []
                for photo in all_media:
                    current_media.append({
                        'name':
                        photo.name,
                        'url':
                        images.get_serving_url(photo.link),
                        'status':
                        photo.status,
                        'primary':
                        photo.primary
                    })
                params['current_media'] = current_media
                self.form = cms_utils.dao_to_form_locality_info(
                    masterdata, forms.BulkPlaygroundForm(self, masterdata))
                self.form = cms_utils.dao_to_form_contact_info(
                    masterdata, self.form)

        params['media_upload_url'] = blobstore.create_upload_url(upload_url)
        return self.render_template('/cms/create_bulk_data.html', **params)

    @user_required
    def post(self, masterdata_id=None):
        params = {}

        if not self.form.validate():
            if masterdata_id is not None and len(masterdata_id) > 1:
                return self.get(masterdata_id)
            else:
                return self.get()

        save = self.request.get('save')
        next = self.request.get('next')
        next_tab = next if next != '' else save
        locality_id = self.request.get('locality_id')

        masterdata = self.form_to_dao(masterdata_id)

        if locality_id is not None:
            logger.info('Locality Id: %s ' % locality_id)
            locality_count = self.process_locality(masterdata.address.locality,
                                                   locality_id,
                                                   constants.PLACES_API_KEY)
            masterdata.address.locality_id = locality_id

        logger.debug('masterdata populated ' + str(masterdata))
        key = self.bulkdataDao.persist(masterdata, self.user_info)
        logger.debug('key ' + str(key))

        if key is not None:
            self.upload_photos(key)
            logger.info('masterdata succesfully created/updated')
            message = ('masterdata succesfully created/updated.')
            self.add_message(message, 'success')
            return self.redirect_to('create-bulk-data', **params)

        logger.error('masterdata creation failed')
        message = ('masterdata creation failed.')
        self.add_message(message, 'error')
        self.form = forms.MasterDataForm(self, masterdata)
        return self.render_template('/cms/create_bulk_data.html', **params)

    @webapp2.cached_property
    def form(self):
        return forms.MasterDataForm(self)

    def upload_photos(self, key):
        upload_files = self.get_uploads()
        if upload_files is not None and len(upload_files) > 0:
            files_count = len(upload_files)
            logger.info('no of files uploaded ' + str(files_count))
            for x in xrange(files_count):
                blob_info = upload_files[x]
                media_obj = Media()
                media_obj.name = self.form.media.__getitem__(x).data['name']
                media_obj.type = constants.PHOTO
                media_obj.status = self.form.media.__getitem__(
                    x).data['status']
                media_obj.primary = self.form.media.__getitem__(
                    x).data['primary']
                media_obj.link = blob_info.key()
                media_obj.url = images.get_serving_url(blob_info.key())
                media_obj.entity_id = key
                media_obj.entity_type = constants.PLAYGROUND
                self.mediaDao.persist(media_obj)
                logger.info('Link to picture file ' + media_obj.name + ', ' +
                            images.get_serving_url(media_obj.link))

    def form_to_dao(self, masterdata_id):
        masterdata = None
        if masterdata_id is not None and len(masterdata_id) > 1:
            masterdata = self.playgroundDao.get_record(long(masterdata_id))
        else:
            masterdata = MasterData()
        masterdata.pg_name = self.form.pg_name.data
        masterdata.sport = self.form.sport.data.lower()

        masterdata.public = self.form.public.data
        masterdata.booking_days = self.form.booking_days.data
        masterdata.regular_time = self.form.regular_time.data
        masterdata.ground_type = self.form.ground_type.data.lower()
        masterdata.surface_type = self.form.surface_type.data.lower()
        masterdata.tot_fields = self.form.tot_fields.data
        masterdata.ground_rules = self.form.ground_rules.data.lower()

        masterdata.tc_name = self.form.tc_name.data
        masterdata.tc_open_days = self.form.tc_open_days.data.lower()
        masterdata.age_limit = self.form.age_limit.data
        masterdata.tc_participants = self.form.tc_participants.data

        masterdata.se_name = self.form.se_name.data
        if self.form.start_datetime.data is not None:
            masterdata.start_datetime = datetime(
                *(self.form.start_datetime.data.timetuple()[:6]))
        if self.form.end_datetime.data is not None:
            masterdata.end_datetime = datetime(
                *(self.form.end_datetime.data.timetuple()[:6]))

        masterdata = cms_utils.form_to_dao_address(self.form, masterdata)
        masterdata = cms_utils.form_to_dao_contact_pg(self.form, masterdata)
        masterdata = cms_utils.form_to_dao_contact_tc(self.form, masterdata)
        masterdata = cms_utils.form_to_dao_contact_se(self.form, masterdata)
        return masterdata

    def create_or_update_business(self, playground):
        if playground.business_id is not None:
            business = self.businessDao.get_record(
                long(playground.business_id.id()))
        else:
            business = Business()
        business.name = playground.name
        business.alias = playground.alias
        business.description = playground.description
        business.contact_info = playground.contact_info
        return business
Ejemplo n.º 3
0
class ManageEventHandler(blobstore_handlers.BlobstoreUploadHandler,
                         BaseHandler):

    businessDao = DaoFactory.create_rw_businessDao()
    eventDao = DaoFactory.create_rw_eventDao()
    mediaDao = DaoFactory.create_rw_mediaDao()

    #@role_required('business')
    @user_required
    def get(self, business_id=None, event_id=None):
        params = {}

        upload_url = self.uri_for('select-for-event')
        continue_url = self.request.get('continue').encode('ascii', 'ignore')
        params[
            'continue_url'] = continue_url if continue_url != '' else upload_url
        status = self.request.get('status')
        event_status = status if status != '' else None
        params['title'] = 'Create New Event'

        if business_id is not None and len(business_id) > 1:
            self.form.business_id = business_id
            if event_id is not None and len(event_id) > 1:
                event = self.eventDao.get_record(event_id)
                params['title'] = 'Update - ' + str(event.name)
                if event_status is not None:
                    logger.info('current status: %s' % event_status)
                    key = self.eventDao.status_change(event, self.user_info)
                    if key is not None:
                        updated_event = self.eventDao.get_record(long(
                            key.id()))
                        logger.info('updated status : %s' %
                                    updated_event.status)
                        if event_status == str(updated_event.status):
                            logger.info('event status could not be changed.')
                            message = ('event status could not be changed.')
                            self.add_message(message, 'error')
                        else:
                            logger.info('event status succesfully changed.')
                            message = ('event status succesfully changed.')
                            self.add_message(message, 'success')
                        return self.redirect(continue_url)
                else:
                    upload_url = self.uri_for('edit-event',
                                              business_id=business_id,
                                              event_id=event_id)
                    all_media = self.mediaDao.get_all_media(
                        event.key, constants.EVENT)
                    current_media = []
                    for photo in all_media:
                        current_media.append({
                            'name':
                            photo.name,
                            'url':
                            images.get_serving_url(photo.link),
                            'status':
                            photo.status,
                            'primary':
                            photo.primary
                        })
                    params['current_media'] = current_media
                    logger.debug('event detail ' + str(event))
                    self.form = cms_utils.dao_to_form_city_info(
                        event, forms.EventForm(self, event))
                    self.form = cms_utils.dao_to_form_contact_info(
                        event, self.form)

                    params['media_upload_url'] = blobstore.create_upload_url(
                        upload_url)
                    return self.render_template('/cms/create_event.html',
                                                **params)
            else:
                upload_url = self.uri_for('create-event',
                                          business_id=business_id)
                params['media_upload_url'] = blobstore.create_upload_url(
                    upload_url)
                return self.render_template('/cms/create_event.html', **params)

        params['entity_name'] = 'Event'
        params['owner_business'] = self.businessDao.query_by_owner(
            self.user_info)
        logger.info('Result Params : ' + str(params['entity_name']))
        return self.render_template('/cms/select_business.html', **params)

    #@role_required('business')
    @user_required
    def post(self, business_id=None, event_id=None):
        params = {}

        if not self.form.validate():
            if business_id is not None and len(business_id) > 0:
                if event_id is not None and len(event_id) > 0:
                    return self.get(business_id, event_id)
                else:
                    return self.get(business_id)
            else:
                return self.get()

        save = self.request.get('save')
        next_fill = self.request.get('next')
        next_tab = next_fill if next_fill != '' else save
        locality_id = self.request.get('locality_id')

        event = self.form_to_dao(event_id)

        if locality_id is not None and len(locality_id) > 0:
            logger.info('Locality Id: %s ' % locality_id)
            locality_count = self.process_locality(event.address.locality,
                                                   locality_id,
                                                   constants.PLACES_API_KEY)
            event.address.locality_id = locality_id
        else:
            event.address.locality = ''
            event.address.locality_id = ''

        logger.debug('event populated ' + str(event))
        if business_id != None and business_id != 'user':
            business = self.businessDao.get_record(business_id)
            business_key = business.key
        else:
            business = self.create_or_update_business(event)
            business_key = self.businessDao.persist(business, self.user_info)

        if business_key is not None:
            logger.info('Business succesfully created for event, ' +
                        business.name)
            event.business_id = business_key
            key = self.eventDao.persist(event, self.user_info)
            logger.debug('key ' + str(key))

            if key is not None:
                self.upload_photos(key)
                logger.info('event succesfully created/updated')
                message = ('event succesfully created/updated.')
                self.add_message(message, 'success')
                if next_tab is not None:
                    if next_tab != 'save':
                        redirect_url = self.uri_for(
                            'edit-event',
                            business_id=event.business_id.id(),
                            event_id=key.id())
                        redirect_url = redirect_url + next_tab
                        logger.info('Url %s' % redirect_url)
                        return self.redirect(redirect_url)
                    else:
                        redirect_url = self.uri_for(
                            'event-details',
                            city_name=event.address.city,
                            entity_id=key.id(),
                            entity_alias=event.alias)
                        return self.redirect(redirect_url)
                        #return self.redirect_to('dashboard', **params)

        logger.error('event creation failed')
        message = ('event creation failed.')
        self.add_message(message, 'error')
        self.form = forms.EventForm(self, event)
        return self.render_template('/cms/create_event.html', **params)

    @webapp2.cached_property
    def form(self):
        return forms.EventForm(self)

    def upload_photos(self, key):
        upload_files = self.get_uploads()
        if upload_files is not None and len(upload_files) > 0:
            files_count = len(upload_files)
            logger.info('no of files uploaded ' + str(files_count))
            for x in xrange(files_count):
                blob_info = upload_files[x]
                media_obj = Media()
                media_obj.name = self.form.media.__getitem__(x).data['name']
                media_obj.type = constants.PHOTO
                media_obj.status = self.form.media.__getitem__(
                    x).data['status']
                media_obj.primary = self.form.media.__getitem__(
                    x).data['primary']
                media_obj.link = blob_info.key()
                media_obj.url = images.get_serving_url(blob_info.key())
                media_obj.entity_id = key
                media_obj.entity_type = constants.EVENT
                self.mediaDao.persist(media_obj)
                logger.info('Link to picture file ' + media_obj.name + ', ' +
                            images.get_serving_url(media_obj.link))

    def form_to_dao(self, event_id):
        event = None
        if event_id is not None and len(event_id) > 1:
            event = self.eventDao.get_record(long(event_id))
        else:
            event = Event()
        event.name = self.form.name.data
        event.sport = self.form.sport.data
        #Create an automatic alias for the event
        event.alias = utils.slugify(self.form.name.data)
        event.caption = self.form.caption.data
        event.description = self.form.description.data
        event.featured = self.form.featured.data
        event.start_datetime = datetime(
            *(self.form.start_datetime.data.timetuple()[:6]))
        event.end_datetime = datetime(
            *(self.form.end_datetime.data.timetuple()[:6]))
        self.form.address.city.data = self.form.city.data  #for city from basic info to address
        event = cms_utils.form_to_dao_address(self.form, event)
        event = cms_utils.form_to_dao_contact_info(self.form, event)
        return event

    def create_or_update_business(self, event):
        if event.business_id is not None:
            business = self.businessDao.get_record(long(
                event.business_id.id()))
        else:
            business = Business()
        business.name = event.name
        business.description = event.description
        business.alias = event.alias
        business.contact_info = event.contact_info
        return business
Ejemplo n.º 4
0
class ManageTrainingCentreHandler(blobstore_handlers.BlobstoreUploadHandler,
                                  BaseHandler):

    businessDao = DaoFactory.create_rw_businessDao()
    trainingCentreDao = DaoFactory.create_rw_trainingCentreDao()
    mediaDao = DaoFactory.create_rw_mediaDao()

    #@role_required('business')
    @user_required
    def get(self, business_id=None, trainingcentre_id=None):
        params = {}

        upload_url = self.uri_for('select-for-trainingcentre')
        continue_url = self.request.get('continue').encode('ascii', 'ignore')
        status = self.request.get('status')
        tc_status = status if status != '' else None
        params['title'] = 'Create New Training Centre'

        if business_id is not None and len(business_id) > 1:
            self.form.business_id = business_id
            params['continue_url'] = continue_url
            if trainingcentre_id is not None and len(trainingcentre_id) > 1:
                trainingcentre = self.trainingCentreDao.get_record(
                    trainingcentre_id)
                params['title'] = 'Update - ' + str(trainingcentre.name)
                if tc_status is not None:
                    logger.info('current status: %s' % tc_status)
                    key = self.trainingCentreDao.status_change(
                        trainingcentre, self.user_info)
                    if key is not None:
                        updated_tc = self.trainingCentreDao.get_record(
                            long(key.id()))
                        logger.info('updated status : %s' % updated_tc.status)
                        if tc_status == str(updated_tc.status):
                            logger.info(
                                'trainingcentre status could not be changed.')
                            message = (
                                'trainingcentre status could not be changed.')
                            self.add_message(message, 'error')
                        else:
                            logger.info(
                                'trainingcentre status succesfully changed.')
                            message = (
                                'trainingcentre status succesfully changed.')
                            self.add_message(message, 'success')
                        return self.redirect(continue_url)
                else:
                    upload_url = self.uri_for(
                        'edit-trainingcentre',
                        business_id=business_id,
                        trainingcentre_id=trainingcentre_id)
                    all_media = self.mediaDao.get_all_media(
                        trainingcentre.key, constants.TRAINING_CENTRE)
                    current_media = []
                    for photo in all_media:
                        current_media.append({
                            'name':
                            photo.name,
                            'url':
                            images.get_serving_url(photo.link),
                            'status':
                            photo.status,
                            'primary':
                            photo.primary
                        })
                    params['current_media'] = current_media
                    self.form = cms_utils.dao_to_form_locality_info(
                        trainingcentre,
                        forms.TrainingCentreForm(self, trainingcentre))
                    self.form = cms_utils.dao_to_form_contact_info(
                        trainingcentre, self.form)

                params['media_upload_url'] = blobstore.create_upload_url(
                    upload_url)
                return self.render_template('/cms/create_trainingcenter.html',
                                            **params)
            else:
                upload_url = self.uri_for('create-trainingcentre',
                                          business_id=business_id)
                params['media_upload_url'] = blobstore.create_upload_url(
                    upload_url)
                return self.render_template('/cms/create_trainingcenter.html',
                                            **params)

        params['continue_url'] = upload_url
        params['entity_name'] = 'Training Centre'
        params['owner_business'] = self.businessDao.query_by_owner(
            self.user_info)
        return self.render_template('/cms/select_business.html', **params)

    #@role_required('business')
    @user_required
    def post(self, business_id=None, trainingcentre_id=None):
        params = {}

        if not self.form.validate():
            if business_id is not None and len(business_id) > 0:
                if trainingcentre_id is not None and len(
                        trainingcentre_id) > 0:
                    return self.get(business_id, trainingcentre_id)
                else:
                    return self.get(business_id)
            else:
                return self.get()

        save = self.request.get('save')
        next_fill = self.request.get('next')
        next_tab = next_fill if next_fill != '' else save
        locality_id = self.request.get('locality_id')

        trainingcentre = self.form_to_dao(trainingcentre_id)
        logger.info('This is debugging for %s' % trainingcentre)

        if locality_id is not None:
            logger.info('Locality Id: %s ' % locality_id)
            locality_count = self.process_locality(
                trainingcentre.address.locality, locality_id,
                constants.PLACES_API_KEY)
            trainingcentre.address.locality_id = locality_id

        logger.debug('trainingcentre populated ' + str(trainingcentre))
        if business_id != None and business_id != 'user':
            business = self.businessDao.get_record(business_id)
            business_key = business.key
        else:
            business = self.create_or_update_business(trainingcentre)
            business_key = self.businessDao.persist(business, self.user_info)

        if business_key is not None:
            logger.info('Business succesfully created for trainingcentre, ' +
                        business.name)
            trainingcentre.business_id = business_key
            key = self.trainingCentreDao.persist(trainingcentre,
                                                 self.user_info)
            logger.debug('key ' + str(key))

            if key is not None:
                self.upload_photos(key)
                logger.info('trainingcentre succesfully created/updated')
                message = ('trainingcentre succesfully created/updated.')
                self.add_message(message, 'success')
                if next_tab is not None:
                    if next_tab != 'save':

                        redirect_url = self.uri_for(
                            'edit-trainingcentre',
                            business_id=trainingcentre.business_id.id(),
                            trainingcentre_id=key.id())
                        logger.debug('this is redirect value: %s' %
                                     redirect_url)
                        redirect_url = redirect_url + next_tab
                        logger.info('Redirect Url %s' % redirect_url)
                        return self.redirect(redirect_url)
                    else:
                        redirect_url = self.uri_for(
                            'tc-details',
                            city_name=trainingcentre.address.city,
                            locality_name=trainingcentre.address.locality,
                            entity_id=key.id(),
                            entity_alias=trainingcentre.alias)
                        return self.redirect(redirect_url)
                        #return self.redirect_to('dashboard', **params)

        logger.error('trainingcentre creation failed')
        message = ('trainingcentre creation failed.')
        self.add_message(message, 'error')
        self.form = forms.TrainingCentreForm(self, trainingcentre)
        return self.render_template('/cms/create_trainingcentre.html',
                                    **params)

    @webapp2.cached_property
    def form(self):
        return forms.TrainingCentreForm(self)

    def upload_photos(self, key):
        upload_files = self.get_uploads()
        if upload_files is not None and len(upload_files) > 0:
            files_count = len(upload_files)
            logger.info('no of files uploaded ' + str(files_count))
            for x in xrange(files_count):
                blob_info = upload_files[x]
                media_obj = Media()
                media_obj.name = self.form.media.__getitem__(x).data['name']
                media_obj.type = constants.PHOTO
                media_obj.status = self.form.media.__getitem__(
                    x).data['status']
                media_obj.primary = self.form.media.__getitem__(
                    x).data['primary']
                media_obj.link = blob_info.key()
                media_obj.url = images.get_serving_url(blob_info.key())
                media_obj.entity_id = key
                media_obj.entity_type = constants.TRAINING_CENTRE
                self.mediaDao.persist(media_obj)
                logger.info('Link to picture file ' + media_obj.name + ', ' +
                            images.get_serving_url(media_obj.link))

    def form_to_dao(self, trainingcentre_id):
        trainingcentre = None
        if trainingcentre_id is not None and len(trainingcentre_id) > 1:
            trainingcentre = self.trainingCentreDao.get_record(
                long(trainingcentre_id))
        else:
            trainingcentre = TrainingCentre()
        trainingcentre.name = self.form.name.data
        trainingcentre.sport = self.form.sport.data
        #Create an automatic alias for the trainingcentre
        trainingcentre.alias = utils.slugify(self.form.name.data)
        trainingcentre.description = self.form.description.data
        trainingcentre.featured = self.form.featured.data
        self.form.address.locality.data = self.form.locality.data  #for locality from basic info to address
        self.form.address.city.data = self.form.city.data  #for city from basic info to address
        trainingcentre = cms_utils.form_to_dao_address(self.form,
                                                       trainingcentre)
        trainingcentre = cms_utils.form_to_dao_contact_info(
            self.form, trainingcentre)
        return trainingcentre

    def create_or_update_business(self, trainingcentre):
        if trainingcentre.business_id is not None:
            business = self.businessDao.get_record(
                long(trainingcentre.business_id.id()))
        else:
            business = Business()
        business.name = trainingcentre.name
        business.description = trainingcentre.description
        business.alias = trainingcentre.alias
        business.contact_info = trainingcentre.contact_info
        return business
Ejemplo n.º 5
0
class ManagePlaygroundHandler(blobstore_handlers.BlobstoreUploadHandler, BaseHandler):

  playgroundDao =  DaoFactory.create_rw_playgroundDao()
  businessDao = DaoFactory.create_rw_businessDao()
  mediaDao = DaoFactory.create_rw_mediaDao()

  @user_required
  def get(self, playground_id=None):
    params = {}
  
    upload_url = self.uri_for('create-playground')
    continue_url = self.request.get('continue').encode('ascii', 'ignore')
    status = self.request.get('status')
    pg_status = status if status != '' else None
    params['title'] = 'Create New Playground'
    
    if playground_id is not None  and len(playground_id) > 1:
      playground = self.playgroundDao.get_record(playground_id)
      params['title'] = 'Update - ' + str(playground.name)
      params['continue_url'] = continue_url
      if pg_status is not None:
        logger.info('current status: %s' % pg_status)
        key = self.playgroundDao.status_change(playground, self.user_info)
        if key is not None:
          updated_pg = self.playgroundDao.get_record(long(key.id()))
          logger.info('updated status : %s' % updated_pg.status)
          if pg_status == str(updated_pg.status):
            logger.info('playground status could not be changed.')
            message = ('playground status could not be changed.')
            self.add_message(message, 'error')
          else:
            logger.info('playground status succesfully changed.')
            message = ('playground status succesfully changed.')
            self.add_message(message, 'success')
          return self.redirect(continue_url)
      else:
        upload_url = self.uri_for('edit-playground', playground_id = playground_id)      
        all_media = self.mediaDao.get_all_media(playground.key, constants.PLAYGROUND)
        current_media = []
        for photo in all_media:
          current_media.append({'name': photo.name, 'url':images.get_serving_url(photo.link), 'status': photo.status, 'primary': photo.primary})
        params['current_media'] = current_media
        self.form = cms_utils.dao_to_form_locality_info(playground, forms.PlaygroundForm(self, playground))
        self.form = cms_utils.dao_to_form_contact_info(playground, self.form)        
      
    params['media_upload_url'] = blobstore.create_upload_url(upload_url)
    return self.render_template('/cms/create_playground.html', **params)

  @user_required
  def post(self, playground_id=None):
    params = {}

    if not self.form.validate():
      if playground_id is not None  and len(playground_id) > 1:
        return self.get(playground_id)
      else:
        return self.get()
    
    save = self.request.get('save')
    next = self.request.get('next')
    next_tab = next if next != '' else save
    locality_id = self.request.get('locality_id')
    
    playground = self.form_to_dao(playground_id)
    
    if locality_id is not None:
      logger.info('Locality Id: %s ' % locality_id)
      locality_count = self.process_locality(playground.address.locality, locality_id, constants.PLACES_API_KEY)    
      playground.address.locality_id = locality_id
      
    logger.debug('playground populated ' + str(playground))
    business = self.create_or_update_business(playground)
    business_key = self.businessDao.persist(business, self.user_info)

    if business_key is not None:
      logger.info('Business succesfully created for playground, ' + business.name)
      playground.business_id = business_key
      key = self.playgroundDao.persist(playground, self.user_info)
      logger.debug('key ' + str(key))

      if key is not None:
        self.upload_photos(key)
        logger.info('playground succesfully created/updated')
        message = ('playground succesfully created/updated.')
        self.add_message(message, 'success')
        if next_tab is not None:
          if next_tab != 'save':
            redirect_url = self.uri_for('edit-playground', playground_id = key.id())
            redirect_url = redirect_url + next_tab
            logger.info('Redirect Url %s' % redirect_url)
            return self.redirect(redirect_url)
          else:
            redirect_url = self.uri_for('pg-details', city_name = playground.address.city, locality_name = playground.address.locality, entity_id = key.id(), entity_alias = playground.alias)
            return self.redirect(redirect_url)
            #return self.redirect_to('dashboard', **params)
    
    logger.error('playground creation failed')
    message = ('playground creation failed.')
    self.add_message(message, 'error')
    self.form = forms.PlaygroundForm(self, playground)
    return self.render_template('/cms/create_playground.html', **params)

  @webapp2.cached_property
  def form(self):
    return forms.PlaygroundForm(self)
    
  def upload_photos(self, key):
    upload_files = self.get_uploads()  
    if upload_files is not None and len(upload_files) > 0:
      files_count = len(upload_files)
      logger.info('no of files uploaded ' + str(files_count))
      for x in xrange(files_count):
        blob_info = upload_files[x]
        media_obj = Media()
        media_obj.name = self.form.media.__getitem__(x).data['name']
        media_obj.type = constants.PHOTO
        media_obj.status = self.form.media.__getitem__(x).data['status']
        media_obj.primary = self.form.media.__getitem__(x).data['primary']
        media_obj.link = blob_info.key()
        media_obj.url = images.get_serving_url(blob_info.key())
        media_obj.entity_id = key
        media_obj.entity_type = constants.PLAYGROUND
        self.mediaDao.persist(media_obj)
        logger.info('Link to picture file ' + media_obj.name + ', ' + images.get_serving_url(media_obj.link))
    
  def form_to_dao(self, playground_id):
    playground = None
    if playground_id is not None  and len(playground_id) > 1:
      playground = self.playgroundDao.get_record(long(playground_id))
    else:
      playground = Playground()
    playground.name = self.form.name.data
    playground.sport = self.form.sport.data.lower()
    #Create an automatic alias for the playground
    playground.alias = utils.slugify(self.form.name.data)
    playground.description = self.form.description.data
    playground.featured = self.form.featured.data
    self.form.address.locality.data = self.form.locality.data   #for locality from basic info to address
    self.form.address.city.data = self.form.city.data   #for city from basic info to address
    playground = cms_utils.form_to_dao_address(self.form, playground)
    playground = cms_utils.form_to_dao_contact_info(self.form, playground)
    return playground
       
  
  def create_or_update_business(self, playground):
    if playground.business_id is not None:
      business = self.businessDao.get_record(long(playground.business_id.id()))
    else:
      business = Business()
    business.name = playground.name
    business.description = playground.description
    business.alias = playground.alias
    business.contact_info = playground.contact_info
    return business
Ejemplo n.º 6
0
class ManageBusinessHandler(blobstore_handlers.BlobstoreUploadHandler,
                            BaseHandler):

    businessDao = DaoFactory.create_rw_businessDao()

    @role_required('business')
    def get(self, business_id=None):
        params = {}
        params['title'] = 'Create New Business'

        upload_url = self.uri_for('create-business')
        if business_id is not None and len(business_id) > 1:
            upload_url = self.uri_for('edit-business', business_id=business_id)
            business = self.businessDao.get_record(business_id)
            params['title'] = 'Update - ' + str(business.name)
            if business.logo:
                params['current_logo'] = images.get_serving_url(business.logo)
            self.form = cms_utils.dao_to_form_contact_info(
                business, forms.BusinessForm(self, business))

        logger.debug('upload_url' + upload_url)
        params['media_upload_url'] = blobstore.create_upload_url(upload_url)
        return self.render_template('/cms/create_business.html', **params)

    @role_required('business')
    def post(self, business_id=None):
        params = {}

        if not self.form.validate():
            if business_id is not None and len(business_id) > 1:
                return self.get(business_id)
            else:
                return self.get()

        business = self.form_to_dao(business_id)
        upload_files = self.get_uploads(
            'logo')  # 'logo' is file upload field in the form
        if upload_files is not None and len(upload_files) > 0:
            blob_info = upload_files[0]
            business.logo = blob_info.key()
            logger.info('Link to logo ' +
                        images.get_serving_url(business.logo))

        logger.debug('business populated ' + str(business))
        key = self.businessDao.persist(business, self.user_info)
        logger.debug('key ' + str(key))
        if key is not None:
            logger.info('Business succesfully created/updated')
            message = ('Business succesfully created/updated.')
            self.add_message(message, 'success')
            return self.redirect_to('dashboard', **params)
        else:
            logger.error('business creation failed')
            message = ('Business creation failed.')
            self.add_message(message, 'error')
            self.form = forms.BusinessForm(self, business)
            return self.render_template('/cms/create_business.html', **params)

    @webapp2.cached_property
    def form(self):
        return forms.BusinessForm(self)

    def form_to_dao(self, business_id):
        business = None
        if business_id is not None and len(business_id) > 1:
            business = self.businessDao.get_record(long(business_id))
            logger.debug('business ' + str(business))
        else:
            business = Business()
        logger.debug('business 2 ' + str(business))
        business.name = self.form.name.data
        #Create an automatic alias for the business
        business.alias = utils.slugify(self.form.name.data)
        business.description = self.form.description.data
        return cms_utils.form_to_dao_contact_info(self.form, business)
Ejemplo n.º 7
0
class ImportHandler(blobstore_handlers.BlobstoreUploadHandler, BaseHandler):

    eventDao = DaoFactory.create_rw_eventDao()
    businessDao = DaoFactory.create_rw_businessDao()
    playgroundDao = DaoFactory.create_rw_playgroundDao()
    trainingCentreDao = DaoFactory.create_rw_trainingCentreDao()

    @user_required
    def get(self):
        params = {}

        upload_url = self.uri_for('import')
        params['title'] = 'Import'
        params['media_upload_url'] = blobstore.create_upload_url(upload_url)
        return self.render_template('/cms/import.html', **params)

    @user_required
    def post(self):
        if not self.form.validate():
            return self.get()

        start_record = int(str(self.request.get('linenum')))
        upload_files = self.get_uploads(
            'importfile')  # 'file' is file upload field in the form
        blob_info = upload_files[0]
        upload_count = self.process_csv(blob_info, start_record)
        self.add_message(
            str(upload_count) + ' entities created successfully.', 'success')
        return self.redirect_to('import')

    def process_csv(self, blob_info, start_record):
        update = {}
        upload_count = 0
        row_count = 0

        blob_reader = blobstore.BlobReader(blob_info.key())
        datareader = csv.reader(blob_reader)

        for row in datareader:
            row_count += 1
            if row_count >= (start_record + 1):  #to skip the header row
                logger.info('Starting to parse %s, %s' % (row_count, row[1]))
                entity_type = row[0].lower()
                update['name'] = utils.stringify(row[1])
                # Name is mandatory for all entities
                if update['name'] == '':
                    logger.error('Name is empty. Skipping this record')
                    continue

                update['locality'] = utils.stringify(row[5]).lower()
                update['city'] = utils.stringify(row[8]).lower()

                #Locality and city mandatory for playground and trainingcentre
                if entity_type != 'event':
                    if update['locality'] == '' or update['city'] == '':
                        logger.error(
                            'Locality or city is empty. Skipping this record')
                        continue
                alias_name = utils.slugify(update['name'].lower())

                try:
                    update['description'] = utils.stringify(row[2])
                    update['sport'] = utils.stringify(row[3]).lower()
                    update['person_name'] = utils.stringify(row[10])
                    update['phone'] = utils.stringify(row[11])
                    update['email'] = utils.stringify(row[12])
                    update['website'] = utils.stringify(row[13])
                    update['facebook'] = utils.stringify(row[18])
                    update['twitter'] = utils.stringify(row[19])
                    update['youtube'] = utils.stringify(row[20])
                    update['gplus'] = utils.stringify(row[21])
                    update['line1'] = utils.stringify(row[6])
                    update['line2'] = utils.stringify(row[7])
                    update['pin'] = int(
                        row[9].strip()) if row[9] != '' else None
                    #update['start_datetime'] = row[22]
                    #update['end_datetime'] = row[23]

                    logger.debug('Constructed Structure for upload ' +
                                 str(update))
                    logger.info('Entity type to be created, ' + entity_type)

                    if entity_type == 'ground':
                        import_data = self.form_to_dao_ground(
                            alias_name, **update)
                    elif entity_type == 'club':
                        import_data = self.form_to_dao_center(
                            alias_name, **update)
                    elif entity_type == 'event':
                        import_data = self.form_to_dao_event(
                            alias_name, **update)

                    # for add locality table
                    if import_data.address.locality != '':
                        place_name = import_data.address.locality
                        logger.info('Place: %s' % place_name)

                        newfeed_url = 'https://maps.googleapis.com/maps/api/place/autocomplete/xml?types=(regions)&input=' + urllib.quote(
                            place_name) + '&key=' + constants.PLACES_API_KEY
                        logging.info('newfeed url %s' % newfeed_url)

                        newroot = self.parse(newfeed_url)
                        auto_status = newroot.getElementsByTagName(
                            'status')[0].firstChild.data
                        logger.info('Auto Status: %s ' % auto_status)

                        if auto_status == 'OK':
                            items = newroot.getElementsByTagName(
                                'prediction')[0]
                            place_id = items.getElementsByTagName(
                                'place_id')[0].firstChild.data
                            place_name = items.getElementsByTagName(
                                'value')[0].firstChild.data  #description
                            logger.info('Place Name: %s Place Id: %s ' %
                                        (place_name, place_id))
                            import_data.address.locality_id = place_id
                            logger.info('Locality Id: %s ' %
                                        import_data.address.locality_id)
                            locality_add = self.process_locality(
                                place_name, place_id, constants.PLACES_API_KEY)
                            #if import_data.address.latlong == '':
                            #locality = self.importDao.query_by_place_id(place_id)
                            #import_data.address.latlong = locality.latlong
                            #logger.info('Geo Location New: %s ' % import_data.address.latlong)
                        else:
                            logger.error('Error: %s' % auto_status)

                    logger.debug('Populated File Data ' + str(import_data))
                    business_key = self.create_or_update_business(
                        alias_name, import_data)
                    import_data.business_id = business_key

                    if entity_type == 'ground':
                        ground = self.playgroundDao.query_by_alias(alias_name)
                        if ground is not None:
                            self.playgroundDao.copy_playground_model(
                                ground, import_data)
                            key = self.playgroundDao.persist(
                                ground, self.user_info)
                            upload_count += 1
                            logger.info(
                                'Playground updated for %s with key %s' %
                                (alias_name, key))
                        else:
                            key = self.playgroundDao.persist(
                                import_data, self.user_info)
                            upload_count += 1
                            logger.info('New playground created for %s' %
                                        (update['name']))
                    elif entity_type == 'club':
                        tc = self.trainingCentreDao.query_by_alias(alias_name)
                        if tc is not None:
                            self.trainingCentreDao.copy_trainingCentre_model(
                                tc, import_data)
                            key = self.trainingCentreDao.persist(
                                tc, self.user_info)
                            upload_count += 1
                            logger.info(
                                'TrainingCentre updated for %s with key %s' %
                                (alias_name, key))
                        else:
                            key = self.trainingCentreDao.persist(
                                import_data, self.user_info)
                            upload_count += 1
                            logger.info('New training centre created for %s' %
                                        (update['name']))
                    elif entity_type == 'event':
                        event = self.eventDao.query_by_alias(alias_name)
                        if event is not None:
                            self.eventDao.copy_event_model(event, import_data)
                            key = self.eventDao.persist(event, self.user_info)
                            upload_count += 1
                            logger.info('Event updated for %s with key %s' %
                                        (alias_name, key))
                        else:
                            key = self.eventDao.persist(
                                import_data, self.user_info)
                            upload_count += 1
                            logger.info('Event created for %s' %
                                        (update['name']))

                    if key is not None:
                        logger.info(
                            str(entity_type) + ' succesfully created/updated')
                    else:
                        logger.error('Already Exist of %s:%s' %
                                     (entity_type, update['name']))

                except StandardError as e:
                    #skipping to next record
                    logger.error('Error occured, %s, for %s' %
                                 (str(e), alias_name))
            else:
                logger.info("skipping record number, %s " % row_count)
        return upload_count

    @webapp2.cached_property
    def form(self):
        return forms.ImportForm(self)

    def upload_photos(self, photos):
        upload_files = self.get_uploads()
        if upload_files is not None and len(upload_files) > 0:
            files_count = len(upload_files)
            logger.info('no of files uploaded ' + str(files_count))
            for x in xrange(files_count):
                blob_info = upload_files[x]
                media_obj = Media()
                media_obj.name = self.form.media.__getitem__(x).data['name']
                media_obj.status = self.form.media.__getitem__(
                    x).data['status']
                media_obj.link = blob_info.key()
                photos.append(media_obj)
                logger.info('Link to picture file ' + media_obj.name + ', ' +
                            images.get_serving_url(media_obj.link))
        return photos

    def create_or_update_business(self, alias_name, import_data):
        business = self.businessDao.query_by_alias(alias_name)

        if business is not None:
            business_key = business.key
            import_data.business_id = business_key
            logger.info('Business Already Exist with Key %s' %
                        str(business_key))
        else:
            try:
                business = Business()
                business.name = import_data.name
                business.description = import_data.description
                business.alias = import_data.alias
                business.contact_info = import_data.contact_info
                business_key = self.businessDao.persist(
                    business, self.user_info)
                import_data.business_id = business_key
                logger.info('New Business Created for %s with key %s' %
                            (alias_name, str(business_key)))
            except StandardError as e:
                #Skip the error and continue
                logger.error('Error occured, %s, for %s' %
                             (str(e), alias_name))
                raise
        return business_key

    def form_to_dao_ground(self, alias_name, **update):
        try:
            playground = Playground()
            playground.name = update['name']
            #Create an automatic alias for the playground
            playground.alias = alias_name
            playground.description = update['description']
            playground.sport = update['sport']
            playground = self.form_to_dao_address_import(playground, **update)
            playground = self.form_to_dao_contact_info_import(
                playground, **update)
            #if playground.photos is None:
            #playground.photos = []
            #self.upload_photos(playground.photos)
        except StandardError as e:
            logger.error('Error occured, %s, for %s:%s' %
                         (str(e), type, update['name']))
            raise
        return playground

    def form_to_dao_center(self, alias_name, **update):
        try:
            trainingcentre = TrainingCentre()
            trainingcentre.name = update['name']
            #Create an automatic alias for the trainingcentre
            trainingcentre.alias = alias_name
            trainingcentre.description = update['description']
            trainingcentre.sport = update['sport']
            trainingcentre = self.form_to_dao_address_import(
                trainingcentre, **update)
            trainingcentre = self.form_to_dao_contact_info_import(
                trainingcentre, **update)
            #if trainingcentre.photos is None:
            #trainingcentre.photos = []
            #self.upload_photos(trainingcentre.photos)
        except StandardError as e:
            logger.error('Error occured, %s, for %s:%s' %
                         (str(e), type, update['name']))
            raise
        return trainingcentre

    def form_to_dao_event(self, alias_name, **update):
        try:
            event = Event()
            event.name = update['name']
            #Create an automatic alias for the event
            event.alias = alias_name
            event.description = update['description']
            event.sport = update['sport']
            #event.start_datetime = update['start_datetime']
            #event.end_datetime = update['end_datetime']
            event = self.form_to_dao_contact_info_import(event, **update)
            #if event.photos is None:
            #event.photos = []
            #self.upload_photos(event.photos)
        except StandardError as e:
            logger.error('Error occured, %s, for %s:%s' %
                         (str(e), type, update['name']))
            raise
        return event

    def form_to_dao_business(self, **update):
        business = Business()
        business.name = update['name']
        #Create an automatic alias for the business
        business.alias = utils.slugify(update['name'])
        business.description = update['description']
        business = self.form_to_dao_contact_info_import(business, **update)
        return business

    def form_to_dao_address_import(self, entity, **update):
        #entity = playground
        try:
            if update['locality'] == '' or update['city'] == '':
                raise StandardError('Locality is empty. Cannot create entity')

            entity.address = Address()
            entity.address.line1 = update['line1'].lower()
            entity.address.line2 = update['line2'].lower()
            entity.address.locality = update['locality'].lower()
            entity.address.city = update['city'].lower()
            entity.address.pin = update['pin']
            lattitude, longitude = get_latlong_from_address(entity.address)
            if lattitude is not None and longitude is not None:
                entity.address.latlong = ndb.GeoPt(lattitude, longitude)
        except StandardError as e:
            logger.error('Error occured, %s, for %s:%s' %
                         (str(e), type, update['name']))
            raise
        return entity

    def form_to_dao_contact_info_import(self, entity, **update):
        try:
            entity.contact_info = ContactInfo()
            if len(update['person_name']) > 0:
                entity.contact_info.person_name = [
                    x.strip() for x in update['person_name'].split(',')
                ]
            if len(update['email']) > 0:
                entity.contact_info.email = [
                    x.strip() for x in update['email'].split(',')
                ]
            if len(update['phone']) > 0:
                entity.contact_info.phone = [
                    x.strip() for x in update['phone'].split(',')
                ]
            entity.contact_info.website = update['website']
            entity.contact_info.facebook = update['facebook']
            entity.contact_info.twitter = update['twitter']
            entity.contact_info.youtube = update['youtube']
            entity.contact_info.gplus = update['gplus']
        except StandardError as e:
            logger.error('Error occured, %s, for %s:%s' %
                         (str(e), type, update['name']))
            raise
        return entity