Ejemplo n.º 1
0
def login_check(self):
	'''	for merchants ONLY
		check if logged in, and return a the headerdata if so. if not, bounce to the login page'''
	session = get_current_session()
	logging.debug(session)
	if session.has_key('loggedIn') == False or session['loggedIn'] == False:
		#not logged in, bounce to login page
		logging.info('Not logged in. . .Bouncing!')
		self.redirect('/merchants/login')
		
	elif session.has_key('loggedIn') == True and session['loggedIn'] == True:

		uid = session['uid']
		
		owner_of = session['owner_of']
		
		logging.info(uid)
		
		headerData = {
			'loggedIn'	: session['loggedIn'],
			'uid'		: enc.decrypt_key(uid),
			'owner_of'	: enc.decrypt_key(owner_of),
			'validated'	: session['validated']
			}
		#return user metadata.
		return headerData
	return
Ejemplo n.º 2
0
def login_check(self):
    '''	for merchants ONLY
		check if logged in, and return a the headerdata if so. if not, bounce to the login page'''
    session = get_current_session()
    logging.debug(session)
    if session.has_key('loggedIn') == False or session['loggedIn'] == False:
        #not logged in, bounce to login page
        logging.info('Not logged in. . .Bouncing!')
        self.redirect('/merchants/login')

    elif session.has_key('loggedIn') == True and session['loggedIn'] == True:

        uid = session['uid']

        owner_of = session['owner_of']

        logging.info(uid)

        headerData = {
            'loggedIn': session['loggedIn'],
            'uid': enc.decrypt_key(uid),
            'owner_of': enc.decrypt_key(owner_of),
            'validated': session['validated']
        }
        #return user metadata.
        return headerData
    return
Ejemplo n.º 3
0
	def get(self):
		try:
			#check login
			headerData = levr_utils.loginCheck(self, True)
			
			#get the owner information
			ownerID = headerData['ownerID']
			ownerID = enc.decrypt_key(ownerID)
			ownerID = db.Key(ownerID)
			owner = levr.BusinessOwner.get(ownerID)
			logging.debug(owner)
			
			#get the business
			business = owner.businesses.get()#TODO: this will be multiple businesses later
			
			template_values = {
				'owner'		: owner,
				'business'	: business,
				'mode'		: '', #which form to show
				'error'		: ''
				}
				
			template = jinja_environment.get_template('templates/editAccount.html')
			self.response.out.write(template.render(template_values))
		except:
			levr.log_error()
Ejemplo n.º 4
0
	def get(self):
		
		businessID = self.request.get('businessID')
		if businessID == '':
			api_utils.send_error(self,'Required parameter not passed: businessID')
			return
		#decrypt uid
		try:
			businessID = db.Key(enc.decrypt_key(businessID))
		except:
			api_utils.send_error(self,'Invalid parameter: businessID')
			return
		#grab the business
#		business = levr.Business.get(businessID)
		
		#call the business
		#twilio credentials
		sid = 'AC4880dbd1ff355288728be2c5f5f7406b'
		token = 'ea7cce49e3bb805b04d00f76253f9f2b'
		twiliourl='https://api.twilio.com/2010-04-01/Accounts/AC4880dbd1ff355288728be2c5f5f7406b/Calls.json'
		
		auth_header = 'Basic '+base64.b64encode(sid+':'+token)
		logging.info(auth_header)
		
		request = {'From':'+16173608582',
					'To':'+16052610083',
					'Url':'http://www.levr.com/api/merchant/twilioanswer',
					'StatusCallback':'http://www.levr.com/api/merchant/twiliocallback'}
		
		result = urlfetch.fetch(url=twiliourl,
								payload=urllib.urlencode(request),
								method=urlfetch.POST,
								headers={'Authorization':auth_header})
								
		logging.info(levr.log_dict(result.__dict__))
Ejemplo n.º 5
0
	def post(self):
		'''Resets password on the database'''
		try:
			password1 = self.request.get('newPassword1')
			password2 = self.request.get('newPassword2')
			uid = self.request.get('id')
			uid = enc.decrypt_key(uid)
			
			if password1 == password2:
				#passwords match
				logging.debug('flag password success')
				encrypted_password = enc.encrypt_password(password1)
				logging.debug(uid)
				owner = levr.BusinessOwner.get(uid)
				owner.pw = encrypted_password
				owner.put()
				
				#log user in and redirect them to merchants/manage
				session = get_current_session()
				session['ownerID'] = enc.encrypt_key(owner.key())#business.key())
				session['loggedIn'] = True
				session['validated'] = owner.validated
				self.redirect('/merchants/manage')
				
			else:
				#passwords do not match
				self.redirect('/merchants/password/reset?id=%s&success=False' % enc.encrypt_key(uid))
		except:
			levr.log_error()
Ejemplo n.º 6
0
	def get(self):
		'''This is for the page where they see info about how to upload via email'''
		try:
			#check login
			headerData = levr_utils.loginCheck(self, True)
			
			#get the owner information
			ownerID = headerData['ownerID']
			ownerID = enc.decrypt_key(ownerID)
			ownerID = db.Key(ownerID)
			owner = levr.BusinessOwner.get(ownerID)
			logging.debug(owner)
			if not owner:
				self.redirect('/merchants')
			
			#get the business
			business = owner.businesses.get()#TODO: this will be multiple businesses later
			
			
			template_values = {
				'headerData':headerData,
				'title'		:'Upload Instructions',
				'owner'		:owner,
				'business'	:business
			}
			
			template = jinja_environment.get_template('templates/emailUpload.html')
			self.response.out.write(template.render(template_values))
		except:
			levr.log_error()
Ejemplo n.º 7
0
	def get(self):
		'''The page where they view info about the widget'''
		try:
			headerData = levr_utils.loginCheck(self, True)
			logging.debug(headerData)
			
			ownerID = headerData['ownerID']
			ownerID = enc.decrypt_key(ownerID)
			
			
			#business info
			business	= levr.Business.all().filter('owner = ',db.Key(ownerID)).get()
			logging.debug(business)
			
			#businessID
			businessID	= enc.encrypt_key(business.key())
			
			#iframe
			frame = "<iframe src='"+levr_utils.URL+"/widget?id="+business.widget_id+"' frameborder='0' width='1000' height='400' >Your Widget</iframe> />"
		
#			frame = "<iframe src='/widget?id="+business.widget_id+"' frameborder='0' width='1000' height='400' >Your Widget</iframe>"
			logging.debug(frame)
			
			
			template_values = {
				'business'		: business,
				'businessID'	: businessID,
				'frame'			: frame
			}
			template = jinja_environment.get_template('templates/manageWidget.html')
			self.response.out.write(template.render(template_values))
		except:
			levr.log_error()
Ejemplo n.º 8
0
	def post(self):
		try:
			#to deploy: change paypaladaptivepayment argument to False (takes out of sandbox)
			#remove email override
	
			#get corID
			corID = enc.decrypt_key(self.request.get('corID'))
			#get cor
			cor = levr.CashOutRequest.get(corID)
			#get the larger amount if money available at paytime is different
			if cor.amount != cor.money_available_paytime:
				amount = cor.money_available_paytime
				cor.note = 'The money available at paytime was greater than when the COR was created, so the paytime balance was used.'
			else:
				amount = cor.amount
			#get ninja
			ninja = levr.Customer.get(cor.key().parent())
			#get payment email
			receiver_email = ninja.payment_email
			receiver_email = "*****@*****.**"
			#Change to false and enter information in above class to deploy
			paypal_init = PaypalAdaptivePayment(True)
			response = paypal_init.initialize_payment(amount,receiver_email,"http://cancel_url.com","http://return_url.com")
			logging.info(response)
		
			if response['paymentExecStatus'] == 'COMPLETED':
				#set cor to "paid"
				cor.status = "paid"
				cor.date_paid = datetime.now()
				cor.payKey = response['payKey']
			
				cor.put()
			
				#for each deal, make paid_out == earned_total
				q = levr.CustomerDeal.gql('WHERE ANCESTOR IS :1',ninja.key())
				for deal in q:
					deal.paid_out = deal.earned_total
					deal.put()
			
				#are number consistent?
				if cor.amount != cor.money_available_paytime:
					#remember to encrypt the key if this is being used for anything
					#other than just error logging
					logging.error('PAY MISMATCH AT UID:' + ninja.key().__str__())
					#send email here later
			
				#set ninja money_available back to 0
				ninja.money_available = 0.0
			
				#increment money_paid for the customer
				ninja.money_paid += amount
			
				#update ninja
				ninja.put()
				logging.info('Payment completed!')

			self.response.out.write(self.request.get(corID) + '<p>Payment status: <strong>' + response['paymentExecStatus'] + '</strong></p><p><a href="/payments/view">Next Request</a></p>')
		except:
			levr.log_error()
Ejemplo n.º 9
0
	def get(self):
		try:
			logging.debug(self.request)
			dealID = self.request.get('id')
			dealID = enc.decrypt_key(dealID)
			db.delete(dealID)
			
			self.redirect('/merchants/manage')
		except:
			levr.log_error()
Ejemplo n.º 10
0
 def post(self):
     #get corID
     corID = enc.decrypt_key(self.request.get('corID'))
     #grab cor
     cor = levr.CashOutRequest.get(corID)
     #add note
     cor.note = self.request.get('note')
     #change status to rejected
     cor.status = 'rejected'
     #update cor
     cor.put()
Ejemplo n.º 11
0
	def post(self):
		#get corID
		corID = enc.decrypt_key(self.request.get('corID'))
		#grab cor
		cor = levr.CashOutRequest.get(corID)
		#add note
		cor.note = self.request.get('note')
		#change status to rejected
		cor.status = 'rejected'
		#update cor
		cor.put()
Ejemplo n.º 12
0
	def get(self):
		try:
			#check login
			headerData = levr_utils.loginCheck(self, True)
			
			#get the owner information
			ownerID = headerData['ownerID']
			ownerID = enc.decrypt_key(ownerID)
			ownerID = db.Key(ownerID)
			owner = levr.BusinessOwner.get(ownerID)
			logging.debug(owner)
			
			#get the business
			business = owner.businesses.get()#TODO: this will be multiple businesses later
			
			#get deal
			dealID = self.request.get('id')
			
			
			#create upload url BEFORE DECRYPTING
			url = '/merchants/editDeal/upload?uid=' + headerData['ownerID'] + '&business='+ enc.encrypt_key(business.key()) +'&deal=' + dealID
			upload_url = blobstore.create_upload_url(url)
			
			
			#decrypt id, get and format deal
			dealID = enc.decrypt_key(dealID)
			deal = levr.Deal.get(dealID)
			deal = levr.phoneFormat(deal, 'manage')
			
			template_values = {
							"edit"		:True,
							"upload_url":upload_url,
							"deal"		:deal,
							"owner"		:owner,
							"business"	:business,
							"headerData":headerData
			}
			template = jinja_environment.get_template('templates/deal.html')
			self.response.out.write(template.render(template_values))
		except:
			levr.log_error()
Ejemplo n.º 13
0
def login_check_mobile(self):
	session = get_current_session()
	logging.debug(session)
	if session.has_key('loggedIn') == False or session['loggedIn'] == False:
		#not logged in, bounce to login page
		logging.info('Not logged in. . .Bouncing!')
		self.redirect('/merchants/mobile/login')
		
	elif session.has_key('loggedIn') == True and session['loggedIn'] == True:
		uid = session['uid']
		
		owner_of = session['owner_of']
		
		meta = {
			'uid'		: enc.decrypt_key(uid),
			'owner_of'	: enc.decrypt_key(owner_of)
			}
		
		logging.info(meta)
		#return user metadata.
		return meta
Ejemplo n.º 14
0
def login_check_mobile(self):
    session = get_current_session()
    logging.debug(session)
    if session.has_key('loggedIn') == False or session['loggedIn'] == False:
        #not logged in, bounce to login page
        logging.info('Not logged in. . .Bouncing!')
        self.redirect('/merchants/mobile/login')

    elif session.has_key('loggedIn') == True and session['loggedIn'] == True:
        uid = session['uid']

        owner_of = session['owner_of']

        meta = {
            'uid': enc.decrypt_key(uid),
            'owner_of': enc.decrypt_key(owner_of)
        }

        logging.info(meta)
        #return user metadata.
        return meta
Ejemplo n.º 15
0
	def post(self):
		try:
			dealID = enc.decrypt_key(self.request.get('deal'))
			logging.debug(dealID)
			deal = levr.CustomerDeal.get(dealID)
			deal.deal_status = 'rejected'
			deal.been_reviewed = True
			deal.reject_message = self.request.get('reject_message')
			deal.put()
			self.redirect('/admin/pending')
		except:
			levr.log_error()
			self.response.out.write('Error rejecting. See logs.')
Ejemplo n.º 16
0
	def get(self):
		try:
			#check login
			headerData = levr_utils.loginCheck(self, True)
			
			#get the owner information
			ownerID = headerData['ownerID']
			ownerID = enc.decrypt_key(ownerID)
			ownerID = db.Key(ownerID)
			owner = levr.BusinessOwner.get(ownerID)
			logging.debug(owner)
			#get the business
			business = owner.businesses.get()#TODO: this will be multiple businesses later
			
			
			#get all deals that are children of the owner ordered by whether or not they are exclusive or not
#			d = levr.Deal.all().ancestor(ownerID).order("is_exclusive").fetch(None)
#			logging.debug(d)
			#get all ninja deals
			d = levr.Deal().all().filter('businessID =', str(business.key())).fetch(None)
#			d += ninja_deals
			#package deals - mostly for getting the correct urls
			deals = []
			for deal in d:
				logging.debug('-----------')
				deals.append(levr.phoneFormat(deal, 'manage'))
			
			
			## ==== Spoofed values ====##
			views = 20
			rank = 21
			redemptions = 23
			
			template_values = {
				'headerData':headerData,
				'title'		:'Manage',
				'owner'		:owner,
				'business'	:business,
				'deals'		:deals,
				'views'		:views,
				'rank'		:rank,
				'redemptions':redemptions
			}
			logging.debug(template_values)
			
			template = jinja_environment.get_template('templates/manageOffers.html')
			self.response.out.write(template.render(template_values))
		except:
			levr.log_error()
Ejemplo n.º 17
0
	def get(self):
		dealID 	= enc.decrypt_key(self.request.get('id'))
		deal	= levr.Deal.get(dealID)
		business= levr.Business.get(deal.businessID)
		deal	= levr.phoneFormat(deal,'widget')
		logging.debug(deal)
		headerData = levr_utils.loginCheck(self,False)
		headerData['loggedIn'] = False
		template_values = {
			'headerData': headerData,
			'deal'		: deal,
			'business'	: business
		}
		jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
		template = jinja_environment.get_template('templates/widget-welcome.html')
		self.response.out.write(template.render(template_values))
Ejemplo n.º 18
0
    def get(self):

        businessID = self.request.get('businessID')
        if businessID == '':
            api_utils.send_error(self,
                                 'Required parameter not passed: businessID')
            return
        #decrypt uid
        try:
            businessID = db.Key(enc.decrypt_key(businessID))
        except:
            api_utils.send_error(self, 'Invalid parameter: businessID')
            return
        #grab the business


#		business = levr.Business.get(businessID)

#call the business
#twilio credentials
        sid = 'AC4880dbd1ff355288728be2c5f5f7406b'
        token = 'ea7cce49e3bb805b04d00f76253f9f2b'
        twiliourl = 'https://api.twilio.com/2010-04-01/Accounts/AC4880dbd1ff355288728be2c5f5f7406b/Calls.json'

        auth_header = 'Basic ' + base64.b64encode(sid + ':' + token)
        logging.info(auth_header)

        request = {
            'From': '+16173608582',
            'To': '+16052610083',
            'Url': 'http://www.levr.com/api/merchant/twilioanswer',
            'StatusCallback': 'http://www.levr.com/api/merchant/twiliocallback'
        }

        result = urlfetch.fetch(url=twiliourl,
                                payload=urllib.urlencode(request),
                                method=urlfetch.POST,
                                headers={'Authorization': auth_header})

        logging.info(levr.log_dict(result.__dict__))
Ejemplo n.º 19
0
	def post(self):
		'''Resets password on the database'''
		password1 = self.request.get('newPassword1')
		password2 = self.request.get('newPassword2')
		uid = self.request.get('id')
		uid = enc.decrypt_key(uid)
		
		if password1 == password2:
			#passwords match
			logging.debug('flag password success')
			encrypted_password = enc.encrypt_password(password1)
			logging.debug(uid)
			user = levr.Customer.get(uid)
			user.pw = encrypted_password
			user.put()
			
			template_values={'success':'True'}
			jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
			template = jinja_environment.get_template('templates/resetPasswordSuccess.html')
			self.response.out.write(template.render(template_values))
		else:
			#passwords do not match
			self.redirect('/password/reset?id=%s&success=False' % enc.encrypt_key(uid))
Ejemplo n.º 20
0
	def get(self):
		'''Creates a list of deal objects to put plugged into an iframe'''
		try:
			#identify the business who is requesting their deals
			businessID 	= self.request.get('id')
			logging.debug(businessID)
			businessID 	= enc.decrypt_key(businessID)
			logging.debug(businessID)
			#grab the deals for the business
			deals = levr.Deal.all().filter('businessID =', businessID).fetch(None)
			logging.debug(deals)
			if not deals:
				#business does not have any deals
				self.response.out.write('No deals!')
				plugs = []
			else:
				#grab/format the necessary information for each deal
				plugs = [levr.phoneFormat(deal,'widget') for deal in deals]
			#check loginstate of user viewing the deal
			headerData = levr_utils.loginCheck(self,False)
			headerData['loggedIn'] = False
#			self.response.out.write(headerData)
			template_values = {
				'headerData'	: headerData,
				'businessID'	: enc.encrypt_key(businessID),
				'deals'			: plugs,
			}
			
			logging.debug(template_values)
		
			jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
			template = jinja_environment.get_template('templates/widget.html')
			self.response.out.write(template.render(template_values))
			
		except:
			levr.log_error()
Ejemplo n.º 21
0
	def post(self):
		try:
			logging.debug(self.request.headers)
			logging.debug(self.request.body)
			logging.debug(self.request.params)
			
			#check login
			headerData = levr_utils.loginCheck(self, True)
			
			#get the owner information
			ownerID = headerData['ownerID']
			ownerID = enc.decrypt_key(ownerID)
			ownerID = db.Key(ownerID)
			owner = levr.BusinessOwner.get(ownerID)
			logging.debug(owner)
			
			password = enc.encrypt_password(self.request.get('password'))
			if owner.pw == password:
				self.response.out.write(True)
			else:
				self.response.out.write(False)
			
		except:
			levr.log_error()
Ejemplo n.º 22
0
	def get(self):
		'''This is the deal upload page'''
		try:
			#check login
			headerData = levr_utils.loginCheck(self, True)
			logging.debug(headerData)
			#get the owner information
			ownerID = headerData['ownerID']
			ownerID = enc.decrypt_key(ownerID)
			ownerID = db.Key(ownerID)
			owner = levr.BusinessOwner.get(ownerID)
			logging.debug(owner)
			
			#get the business
			business = owner.businesses.get()#TODO: this will be multiple businesses later
			
			#create tags from the business
			tags = business.create_tags()
			
			#create the upload url
			url = '/merchants/deal/upload?uid=' + headerData['ownerID'] + '&business=' + enc.encrypt_key(business.key())
			logging.debug(url)
			upload_url = blobstore.create_upload_url(url)
			
			#consolidate the values
			template_values = {
							"tags"			: tags,
							"upload_url"	: upload_url,
							"deal"			: None,
							"business"		: business, #TODO need to grab multiple businesses later
							"owner"			: owner
			}
			template = jinja_environment.get_template('templates/deal.html')
			self.response.out.write(template.render(template_values))
		except:
			levr.log_error()
Ejemplo n.º 23
0
    def post(self):
        try:
            #to deploy: change paypaladaptivepayment argument to False (takes out of sandbox)
            #remove email override

            #get corID
            corID = enc.decrypt_key(self.request.get('corID'))
            #get cor
            cor = levr.CashOutRequest.get(corID)
            #get the larger amount if money available at paytime is different
            if cor.amount != cor.money_available_paytime:
                amount = cor.money_available_paytime
                cor.note = 'The money available at paytime was greater than when the COR was created, so the paytime balance was used.'
            else:
                amount = cor.amount
            #get ninja
            ninja = levr.Customer.get(cor.key().parent())
            #get payment email
            receiver_email = ninja.payment_email
            receiver_email = "*****@*****.**"
            #Change to false and enter information in above class to deploy
            paypal_init = PaypalAdaptivePayment(True)
            response = paypal_init.initialize_payment(amount, receiver_email,
                                                      "http://cancel_url.com",
                                                      "http://return_url.com")
            logging.info(response)

            if response['paymentExecStatus'] == 'COMPLETED':
                #set cor to "paid"
                cor.status = "paid"
                cor.date_paid = datetime.now()
                cor.payKey = response['payKey']

                cor.put()

                #for each deal, make paid_out == earned_total
                q = levr.CustomerDeal.gql('WHERE ANCESTOR IS :1', ninja.key())
                for deal in q:
                    deal.paid_out = deal.earned_total
                    deal.put()

                #are number consistent?
                if cor.amount != cor.money_available_paytime:
                    #remember to encrypt the key if this is being used for anything
                    #other than just error logging
                    logging.error('PAY MISMATCH AT UID:' +
                                  ninja.key().__str__())
                    #send email here later

                #set ninja money_available back to 0
                ninja.money_available = 0.0

                #increment money_paid for the customer
                ninja.money_paid += amount

                #update ninja
                ninja.put()
                logging.info('Payment completed!')

            self.response.out.write(
                self.request.get(corID) + '<p>Payment status: <strong>' +
                response['paymentExecStatus'] +
                '</strong></p><p><a href="/payments/view">Next Request</a></p>'
            )
        except:
            levr.log_error()
Ejemplo n.º 24
0
	def get(self):
		#get inputs
		'''Returns ONLY an image for a deal specified by dealID
		Gets the image from the blobstoreReferenceProperty deal.img'''
		try:
			logging.info('img')
			dealID 	= enc.decrypt_key(self.request.get('dealID'))
			size 	= self.request.get('size')
			logging.debug(dealID)
			logging.debug(size)
			
			#get deal object
			deal = db.get(dealID)

			#get the blob
			blob_key = deal.img
			
			logging.debug(dir(blob_key.properties))
			#read the blob data into a string !!!! important !!!!
			blob_data = blob_key.open().read()
			
			#pass blob data to the image handler
			img			= images.Image(blob_data)
			#get img dimensions
			img_width	= img.width
			img_height	= img.height
			logging.debug(img_width)
			logging.debug(img_height)
			
			#define output parameters
			if size == 'dealDetail':
				#view for top of deal screen
				aspect_ratio 	= 3. 	#width/height
				output_width 	= 640.	#arbitrary standard
			elif size == 'list':
				#view for in deal or favorites list
				aspect_ratio	= 1.	#width/height
				output_width	= 200.	#arbitrary standard
			elif size == 'fullSize':
				#full size image
				aspect_ratio	= float(img_width)/float(img_height)
				output_width	= float(img_width)
	#			self.response.out.write(deal.img)
			elif size == 'webShare':
				aspect_ratio	= 4.
				output_width	= 600.
			elif size == 'facebook':
				aspect_ratio 	= 1.
				output_width	= 250.
			elif size == 'emptySet':
				aspect_ratio	= 3.
				output_width	= 640.
			elif size == 'widget':
				aspect_ratio	= 1.
				output_width	= 150.
			else:
				raise Exception('invalid size parameter')
				
				##set this to some default for production
			#calculate output_height from output_width
			output_height	= output_width/aspect_ratio
			
			##get crop dimensions
			if img_width > img_height*aspect_ratio:
				#width must be cropped
				w_crop_unscaled = (img_width-img_height*aspect_ratio)/2
				w_crop 	= float(w_crop_unscaled/img_width)
				left_x 	= w_crop
				right_x = 1.-w_crop
				top_y	= 0.
				bot_y	= 1.
			else:
				#height must be cropped
				h_crop_unscaled = (img_height-img_width/aspect_ratio)/2
				h_crop	= float(h_crop_unscaled/img_height)
				left_x	= 0.
				right_x	= 1.
				top_y	= h_crop
				bot_y	= 1.-h_crop
		
			#crop image to aspect ratio
			img.crop(left_x,top_y,right_x,bot_y)
			logging.debug(img)
			
			#resize cropped image
			img.resize(width=int(output_width),height=int(output_height))
			logging.debug(img)
			output_img = img.execute_transforms(output_encoding=images.JPEG)
#			logging.debug(output_img)
		except:
			levr.log_error(self.request.body)
			output_img = None
		finally:
			try:
				self.response.headers['Content-Type'] = 'image/jpeg'
				self.response.out.write(output_img)
			except:
				levr.log_error()
Ejemplo n.º 25
0
    def post(self):

        logging.debug(self.get_uploads())
        if self.get_uploads():  #will this work?
            upload = self.get_uploads()[0]
            logging.info(upload)
            blob_key = upload.key()
            img_key = blob_key
            upload_flag = True
        else:
            upload_flag = False
            raise KeyError('Image was not uploaded')

        uid = enc.decrypt_key(self.request.get('uid'))
        businessID = enc.decrypt_key(self.request.get('businessID'))
        deal_text = self.request.get('deal_text')
        description = self.request.get('description')
        contentID = self.request.get('contentID')

        logging.info(uid)
        logging.info(businessID)
        logging.info(deal_text)
        logging.info(description)

        business = levr.Business.get(businessID)
        user = levr.Customer.get(uid)

        params = {
            'uid': user,
            'business_name': business.business_name,
            'geo_point': business.geo_point,
            'vicinity': business.vicinity,
            'types': ','.join(
                map(str, business.types)
            ),  #phone sends in a comma separated string, types is stored as a list
            'deal_description': description,
            'deal_line1': deal_text,
            'distance': -1,  #is -1 if unknown = double
            'development': False,
            'img_key': img_key
        }

        dealID = levr.dealCreate(params, 'phone_new_business')

        #fire off a task to do the image rotation stuff
        task_params = {'blob_key': str(img_key)}
        taskqueue.add(url='/tasks/checkImageRotationTask',
                      payload=json.dumps(task_params))

        #track event via mixpanel (asynchronous)
        # try:
        # 			properties = {
        # 				'time'				:	time.time(),
        # 				'distinct_id'		:	enc.encrypt_key(user.key()),
        # 				'mp_name_tag'		:	user.display_name
        # 			}
        # 			mp_track.track('Deal uploaded','ab1137787f393161bd481e2756b77850',properties)
        #
        # 			to_increment = {
        # 						"Deals uploaded"	:	1
        # 			}
        #
        # 			mp_track.increment(enc.encrypt_key(user.key()),'ab1137787f393161bd481e2756b77850',to_increment)
        #
        # 		except:
        # 			levr.log_error()

        logging.info('/mobile/upload/complete/?uid=' +
                     urllib.quote(enc.encrypt_key(uid)))
        self.redirect('/mobile/upload/complete/?uid=' +
                      urllib.quote(enc.encrypt_key(uid)))
Ejemplo n.º 26
0
	def post(self):
		
		logging.debug(self.get_uploads())
		if self.get_uploads(): #will this work?
			upload	= self.get_uploads()[0]
			logging.info(upload)
			blob_key= upload.key()
			img_key = blob_key
			upload_flag = True
		else:
			upload_flag = False
			raise KeyError('Image was not uploaded')
		
		uid = enc.decrypt_key(self.request.get('uid'))
		businessID = enc.decrypt_key(self.request.get('businessID'))
		deal_text = self.request.get('deal_text')
		description = self.request.get('description')
		contentID = self.request.get('contentID')
		
		logging.info(uid)
		logging.info(businessID)
		logging.info(deal_text)
		logging.info(description)
		
		business = levr.Business.get(businessID)
		user = levr.Customer.get(uid)
		
		params = {
					'uid'				: user,
					'business_name'		: business.business_name,
					'geo_point'			: business.geo_point,
					'vicinity'			: business.vicinity,
					'types'				: ','.join(map(str, business.types)),	#phone sends in a comma separated string, types is stored as a list
					'deal_description'	: description,
					'deal_line1'		: deal_text,
					'distance'			: -1, #is -1 if unknown = double
					'development'		: False,
					'img_key'			: img_key
					}

		dealID = levr.dealCreate(params,'phone_new_business')
		
		#fire off a task to do the image rotation stuff
		task_params = {
			'blob_key'	:	str(img_key)
		}
		taskqueue.add(url='/tasks/checkImageRotationTask',payload=json.dumps(task_params))
		
		#track event via mixpanel (asynchronous)
		# try:
# 			properties = {
# 				'time'				:	time.time(),
# 				'distinct_id'		:	enc.encrypt_key(user.key()),		
# 				'mp_name_tag'		:	user.display_name
# 			}
# 			mp_track.track('Deal uploaded','ab1137787f393161bd481e2756b77850',properties)
# 			
# 			to_increment = {
# 						"Deals uploaded"	:	1
# 			}
# 			
# 			mp_track.increment(enc.encrypt_key(user.key()),'ab1137787f393161bd481e2756b77850',to_increment)
# 			
# 		except:
# 			levr.log_error()
		
		
		logging.info('/mobile/upload/complete/?uid='+urllib.quote(enc.encrypt_key(uid)))
		self.redirect('/mobile/upload/complete/?uid='+urllib.quote(enc.encrypt_key(uid)))
Ejemplo n.º 27
0
    def get(self):
        #get inputs
        '''Returns ONLY an image for a deal specified by dealID
		Gets the image from the blobstoreReferenceProperty deal.img'''
        try:
            logging.info('img')
            dealID = enc.decrypt_key(self.request.get('dealID'))
            size = self.request.get('size')
            logging.debug(dealID)
            logging.debug(size)

            #get deal object
            deal = db.get(dealID)

            #get the blob
            blob_key = deal.img

            logging.debug(dir(blob_key.properties))
            #read the blob data into a string !!!! important !!!!
            blob_data = blob_key.open().read()

            #pass blob data to the image handler
            img = images.Image(blob_data)
            #get img dimensions
            img_width = img.width
            img_height = img.height
            logging.debug(img_width)
            logging.debug(img_height)

            #define output parameters
            if size == 'dealDetail':
                #view for top of deal screen
                aspect_ratio = 3.  #width/height
                output_width = 640.  #arbitrary standard
            elif size == 'list':
                #view for in deal or favorites list
                aspect_ratio = 1.  #width/height
                output_width = 200.  #arbitrary standard
            elif size == 'fullSize':
                #full size image
                aspect_ratio = float(img_width) / float(img_height)
                output_width = float(img_width)

    #			self.response.out.write(deal.img)
            elif size == 'webShare':
                aspect_ratio = 4.
                output_width = 600.
            elif size == 'facebook':
                aspect_ratio = 1.
                output_width = 250.
            elif size == 'emptySet':
                aspect_ratio = 3.
                output_width = 640.
            elif size == 'widget':
                aspect_ratio = 1.
                output_width = 150.
            else:
                raise Exception('invalid size parameter')

                ##set this to some default for production
            #calculate output_height from output_width
            output_height = output_width / aspect_ratio

            ##get crop dimensions
            if img_width > img_height * aspect_ratio:
                #width must be cropped
                w_crop_unscaled = (img_width - img_height * aspect_ratio) / 2
                w_crop = float(w_crop_unscaled / img_width)
                left_x = w_crop
                right_x = 1. - w_crop
                top_y = 0.
                bot_y = 1.
            else:
                #height must be cropped
                h_crop_unscaled = (img_height - img_width / aspect_ratio) / 2
                h_crop = float(h_crop_unscaled / img_height)
                left_x = 0.
                right_x = 1.
                top_y = h_crop
                bot_y = 1. - h_crop

            #crop image to aspect ratio
            img.crop(left_x, top_y, right_x, bot_y)
            logging.debug(img)

            #resize cropped image
            img.resize(width=int(output_width), height=int(output_height))
            logging.debug(img)
            output_img = img.execute_transforms(output_encoding=images.JPEG)


#			logging.debug(output_img)
        except:
            levr.log_error(self.request.body)
            output_img = None
        finally:
            try:
                self.response.headers['Content-Type'] = 'image/jpeg'
                self.response.out.write(output_img)
            except:
                levr.log_error()
Ejemplo n.º 28
0
def dealCreate(params,origin,upload_flag=True,**kwargs):
	'''
	
	@param params:
	@type params:
	@param origin:
	@type origin:
	@param upload_flag:
	@type upload_flag:
	
	@keyword expires: sets the expiration on a deal. If a merchant uploads,
	  expiration can be passed as 'never' and the deal will never expire
	
	'''
	logging.debug('DEAL CREATE')
	
	logging.debug("origin: "+str(origin))
	logging.debug(log_dict(params))
	
	
	logging.debug("image was uploaded: "+str(upload_flag))
	#init tags list for deal
	tags = []
	
	#business information - never create business unless old phone
		#just want to get tags to store on deal
	#get deal information
	#create deals with appropriate owners
	
	#==== deal information ====#
	
	
	#===========================================================================
	# #==== business stuff ====#
	#===========================================================================
	if origin == 'phone_new_business':
		#The business to which a deal is being uploaded is not targeted
		logging.debug('origin is phone, new business being added')
		
		
		#business name
		if 'business_name' in params:
			business_name = params['business_name']
			logging.debug("business name: "+str(business_name))
		else:
			raise Exception('business_name not in params')
		#geo point
		
		if 'geo_point' in params:
			geo_point = params['geo_point']
			logging.debug("geo point: "+str(geo_point))
			#create geohash from geopoint
			geo_hash = geohash.encode(geo_point.lat,geo_point.lon)
		else:
			raise Exception('geo_point not in params')
		
		#vicinity
		if 'vicinity' in params:
			vicinity = params['vicinity']
			logging.debug("vicinity: "+str(vicinity))
		else:
			raise Exception('vicinity not in params')
		
		
		#types
		if 'types' in params:
			types = params['types']
			types = tagger(types)
		else:
			raise KeyError('types not in params')
		#check if business exists - get businessID
		business = Business.all().filter('business_name =',business_name).filter('vicinity =',vicinity).get()
		logging.debug('start business info')
		logging.debug(log_model_props(business))
		logging.debug('end business info')
		
		if not business:
			logging.debug('business doesnt exist')
			#if a business doesn't exist in db, then create a new one
			business = Business()
			logging.debug(log_model_props(business))
			
			
			
			#add data to the new business
			business.business_name 	= business_name
			business.vicinity 		= vicinity
			business.geo_point		= geo_point
			business.types			= types
			business.geo_hash		= geo_hash
			
			#put business
			business.put()
			
			#fire off a task to check the foursquare similarity
			task_params = {
				'geo_str'		:	str(business.geo_point),
				'query'			:	business.business_name,
				'key'			:	str(business.key())
			}
			
			#if no foursquare business exists in the database, this should try to find a foursquare business and transfer information to it
			#what if there is already a foursquare business in the database?
			
			taskqueue.add(url='/tasks/businessHarmonizationTask',payload=json.dumps(task_params))
			
			
		else:
			logging.debug('business exists')
			#business exists- grab its tags
		
		
		#grab the businesses tags
		tags.extend(business.create_tags())
		#get businessID - not encrypted - from database
		businessID = business.key()
		logging.debug("businessID: "+str(businessID))
		
		#Create tags
		
		logging.debug('-------------------------------------------')
		logging.debug(tags)
	elif origin == 'phone_merchant':
		logging.info('phone_merchant, so do not create new business')
		business = params['business']
		tags.extend(business.create_tags())
		
		#grab all the other information that needs to go into the deals
		businessID		= str(business.key())
		business_name 	= business.business_name
		geo_point		= business.geo_point
		vicinity		= business.vicinity
		geo_hash		= business.geo_hash
	else:
		#BusinessID was passed, grab the business
		logging.debug('not oldphoone')
		
		if 'business' in params:
			businessID = params['business']
			businessID	= enc.decrypt_key(businessID)
			businessID	= db.Key(businessID)
			business	= Business.get(businessID)
		else:
			raise KeyError('business not passed in params')
		#get the tags from the business
		tags.extend(business.create_tags())
		
		#grab all the other information that needs to go into the deals
		business_name 	= business.business_name
		geo_point		= business.geo_point
		vicinity		= business.vicinity
		geo_hash		= business.geo_hash
		

	logging.debug('!!!!!')
	#===========================================================================
	# #====Deal Information Lines ====#
	#===========================================================================
	#deal line 1
	if 'deal_line1' in params:
		deal_text	= params['deal_line1'].decode()
		tags.extend(tagger(deal_text))
	else:
		raise KeyError('deal_line1 not passed in params')
	
	#deal line 2
	if origin != 'phone_existing_business' and origin != 'phone_new_business':
		if 'deal_line2' in params:
			secondary_name = params['deal_line2']
		else:
			secondary_name = False
		logging.debug(secondary_name)
		if secondary_name:
			#deal is bundled
			logging.debug('deal is bundled')
			tags.extend(tagger(secondary_name))
			logging.info(tags)
			deal_type = 'bundle'
		else:
			#deal is not bundled
#			'deal is NOT bundled'
			deal_type = 'single'
	else:
		#phone uploaded deals do not pass deal_line2
		deal_type = 'single'
	
	#description
	if 'deal_description' in params:
		description = params['deal_description'].decode()
		#truncate description to a length of 500 chars
		description = description[:500]
		tags.extend(tagger(description))
	else:
		raise KeyError('deal_description not passed in params')
	
	
	
	
	#==== create the deal entity ====#
	if origin == 'phone_merchant':
		logging.info('Origin from phone_merchant')
		user = params['user']
		
		if user.tester:
			deal_status = 'test'
		else:
			deal_status = 'active'
		
		
		
		deal = Deal(
				parent = user,
				is_exclusive = True,
				deal_status = deal_status,
				origin = 'merchant',
				pin_color = 'green',
				)
		
	elif origin	=='phone_existing_business' or origin == 'phone_new_business':
		#phone deals are the child of a ninja
		logging.debug('STOP!')
		uid = params['uid']
		
		# If it is one of the founders uploading a deal, then it should be uploaded by a rando ninja
		admin_users = ['Carl D.','Patch W.','Alonso H.','Ethan S.','Patrick W.','Pat W.']
		owner = Customer.get(uid)
		if owner.display_name in admin_users:
			undead_ninjas = Customer.all(keys_only=True).filter('email',UNDEAD_NINJA_EMAIL).fetch(None)
			uid = random.choice(undead_ninjas)
		
		deal = Deal(
						parent			= uid,
						is_exclusive	= False
						)
		
		if 'shareURL' in params:
			shareURL = params['shareURL']
			if shareURL:
				#shareURL was passed and is not empty
				logging.debug("shareURL: "+str(shareURL))
				share_id = shareURL.split('/')[-1] #grab share id
				logging.debug("share_id: "+str(share_id))
				deal.share_id = share_id
		
		
		
		development = params.get('development',False)
		if development:
			deal.deal_status = 'test'
		
		deal.date_end = datetime.now() + timedelta(days=7)
	
	#==== Link deal to blobstore image ====#
	if upload_flag == True:
		#an image has been uploaded, and the blob needs to be tied to the deal
		logging.debug('image uploaded')
		#if an image has been uploaded, add it to the deal. otherwise do nothing.
		#assumes that if an image already exists, that it the old one has been deleted elsewhere
		blob_key = params['img_key']
		deal.img= blob_key
	else:
		#an image was not uploaded. do nothing
		logging.debug('image not uploaded')
	
	
	
	
	
	
	#add the data
	try:
		deal.business = business
	except:
		log_error()
	deal.deal_text 			= deal_text
	deal.deal_type			= deal_type
	deal.description 		= description
	deal.tags				= list(set(tags)) #list->set->list removes duplicates
	deal.business_name		= business_name
	deal.businessID			= str(businessID)
	deal.vicinity			= vicinity
	deal.geo_point			= geo_point
	deal.geo_hash			= geo_hash
	
	#secondary_name
	if deal_type == 'bundle':
		deal.secondary_name = secondary_name
	
	
	
	#put the deal
	deal.put()
	
	remove_memcache_key_by_deal(deal)
	
	
	#dealput is the deal key i.e. dealID
	logging.debug(log_model_props(deal))
	logging.debug(log_model_props(business))
	
#	share_url = create_share_url(deal)

	
	if origin == 'phone_existing_business' or origin =='phone_new_business':
		#needs share url and dealID
		return deal
	else:
		#return share url
		return deal
Ejemplo n.º 29
0
    def post(self):
        try:
            logging.info('uploadDeal')
            uid = enc.decrypt_key(self.request.get('uid'))
            user = levr.Customer.get(uid)
            logging.debug(levr_utils.log_model_props(user, ['alias', 'email']))
            logging.debug(self.request.params)
            #make sure than an image is uploaded
            logging.debug(self.get_uploads())
            if self.get_uploads():  #will this work?
                upload = self.get_uploads()[0]
                blob_key = upload.key()
                img_key = blob_key
            else:
                raise Exception('Image was not uploaded')

            #screen for businessID to determine which mode of upload we are receiving
            if self.request.get('businessID'):
                logging.debug('targeted business')
                #we are on iphone
                origin = 'phone_existing_business'
                params = {
                    'uid': self.request.get('uid'),
                    'business': self.request.get('businessID'),
                    'deal_description': self.request.get('deal_description'),
                    'deal_line1': self.request.get('deal_line1'),
                    'distance':
                    self.request.get('distance'),  #is -1 if unknown = double
                    'img_key': img_key
                }


#				(share_url,deal_entity) = levr_utils.dealCreate(params,'phone_existing_business')
            else:
                logging.debug('untargeted business')
                #we are on android
                origin = 'phone_new_business'
                params = {
                    'uid': self.request.get('uid'),
                    'business_name': self.request.get('businessName'),
                    'geo_point': self.request.get('geoPoint'),
                    'vicinity': self.request.get('vicinity'),
                    'types': self.request.get('types'),
                    'deal_description': self.request.get('deal_description'),
                    'deal_line1': self.request.get('deal_line1'),
                    'distance':
                    self.request.get('distance'),  #is -1 if unknown = double
                    'img_key': img_key
                }

            #create the deal using the origin specified
            (share_url, deal_entity) = levr_utils.dealCreate(params, origin)

            #grab deal information for sending back to phone
            deal = levr.phoneFormat(deal_entity, 'list')

            #Return Info..
            toEcho = {
                "success": True,
                "data": {
                    "shareURL": share_url,
                    "deal": deal
                }
            }
            logging.debug(levr_utils.log_dict(toEcho))
            self.response.out.write(json.dumps(toEcho))
        except:
            levr.log_error(self.request.body)
            toEcho = {"success": False}  #,"data":{"shareURL":share_url}}
            self.response.out.write(json.dumps(toEcho))
Ejemplo n.º 30
0
    def post(self):
        #decode the input JSON and pull out the action parameter
        try:
            decoded = json.loads(self.request.body)
            action = decoded["action"]
            logging.info(action)
            try:
                uid = enc.decrypt_key(decoded["in"]["uid"])
                user = levr.Customer.get(uid)
                logging.debug(
                    levr_utils.log_model_props(user, ['alias', 'email']))
            except Exception, e:
                #				logging.debug(uid)
                logging.debug(e)

            #switch action
            #***************signup************************************************
            if action == "signup":
                logging.info('signup')
                #grab email/password from request body
                email = decoded["in"]["email"]
                alias = decoded["in"]["alias"]
                pw = decoded["in"]["pw"]
                toEcho = levr_utils.signupCustomer(email, alias, pw)

            #***************login*************************************************
            elif action == "login":
                logging.info('login')
                #grab email/password from request body
                email_or_owner = decoded["in"]["email_or_owner"]
                pw = decoded["in"]["pw"]

                toEcho = levr_utils.loginCustomer(email_or_owner, pw)

            #***************dealResults************************************************
            elif action == "popularItems":
                logging.info('popularItems')
                lat = decoded['in']['latitude']
                lon = decoded['in']['longitude']

                request_point = levr.geo_converter(str(lat) + "," + str(lon))

                #get all deals in the area
                deals = levr_utils.get_deals_in_area(['all'], request_point)

                #compile a list of all of the tags
                tags = []
                for deal in deals:
                    tags.extend(list(set(deal.tags)))
                tags.sort()
                logging.debug(tags)

                #convert list of all tags to a dict of key=tag, val=frequency
                count = {}
                for tag in tags:
                    #					logging.debug(tag in count)
                    if tag in count:
                        count[tag] += 1
                    else:
                        count[tag] = 1

                #DEBUG
                #convert dict of tag:freq into list of tuples
                tuple_list1 = []
                for key in count:
                    tuple_list1.append((count[key], key))
                tuple_list1.sort()
                tuple_list1.reverse()
                logging.debug(tuple_list1)
                #/DEBUG

                #remove unwanted stuff
                new_count = {}
                for tag in count:
                    #search occurs more than once
                    if count[tag] > 1:
                        #tag is not a number
                        if tag.isdigit() == False:
                            #tag is not in blacklist
                            if tag not in blacklist:
                                new_count[tag] = count[tag]

#				logging.debug(levr_utils.log_dict(count))

#convert dict of tag:freq into list of tuples
                tuple_list = []
                for key in new_count:
                    tuple_list.append((new_count[key], key))
                tuple_list.sort()
                tuple_list.reverse()

                logging.debug(tuple_list)
                #				for i in tuple_list:
                #					logging.debug(i)

                #select only the most popular ones, and convert to list
                word_list = [x[1] for x in tuple_list]

                #if the popular items list is longer than 6, send entire list, else only send 6
                logging.debug(word_list.__len__())
                if word_list.__len__() < 6:
                    popularItems = word_list
                else:
                    popularItems = word_list[:6]

                data = {'popularItems': popularItems}
                toEcho = {'success': True, 'data': data}

            elif action == "dealResults":
                logging.info('dealResults')
                logging.info(decoded['in'])
                #grab primaryCat from the request body
                primaryCat = decoded["in"]["primaryCat"]
                #search term
                #				start 		= decoded["in"]["start"]
                #starting index of search results
                #!!!not used
                numResults = decoded["in"]["size"]
                geo_point = decoded["in"]["geoPoint"]
                try:
                    precision = int(decoded['in']['precision'])
                except:
                    precision = 5

                logging.debug(numResults)
                #length of search results list
                #should be None if we want all results

                #normalize search query
                primaryCat = primaryCat.lower()

                ###filter by location - get neighborhoods
                request_point = levr.geo_converter(geo_point)
                #

                #normalize search query
                primaryCat = primaryCat.lower()
                #otherwise, search based on the tags
                tags = levr.tagger(primaryCat)
                logging.debug(tags)

                #batch get results. here is where we would set the number of results we want and the offset
                results = levr_utils.get_deals_in_area(tags, request_point,
                                                       precision)

                logging.info('number of deals fetched: ' +
                             str(results.__len__()))
                #define an empty "dealResults" LIST, and initialize the counter to 0
                #initialize isEmpty to 1
                isEmpty = True
                dealResults = []
                #iterate over the results
                #Want to grab deal information for each category
                for result in results:
                    #					logging.info('Rank: ' + str(result.rank))
                    #break if results limit is hit
                    isEmpty = False
                    #trade an object for a phone-formatted dictionary
                    deal = levr.phoneFormat(result, 'list', primaryCat)
                    #indicate that this is not a sentinel
                    deal['isSentinel'] = False
                    logging.debug(result.geo_hash)
                    #push the whole dictionary onto a list
                    dealResults.append(deal)
                    #increment the counter
#					resultsPushed += 1
                logging.debug(dealResults.__len__())

                ##debug
                #				deals = levr.Deal.all().fetch(None)
                #				for d in deals:
                #					logging.debug(d.geo_hash)

                #				############OLD
                #				#normalize search query
                #				primaryCat = primaryCat.lower()
                #
                #
                #				#build search query
                #				q = levr.Deal.all()
                #
                #				logging.debug("total number of deals: "+str(q.count()))
                #				#only active deals
                #				q.filter('deal_status','active')
                #				#primaryCat will be mapresults to return everything
                #				if primaryCat == 'all':
                #					#get all deals - no filter
                #					logging.debug('all')
                #				else:
                #					logging.debug('not all')
                #					#normalize search query
                #					primaryCat = primaryCat.lower()
                #					#otherwise, search based on the tags
                #					tags = levr.tagger(primaryCat)
                #					logging.debug(tags)
                #					#grab all deals where primary_cat is in tags
                #					for tag in tags:
                #						logging.debug('tag: '+str(tag))
                #						q.filter('tags =',tag)
                #
                #				###filter by location
                #				request_point = levr.geo_converter(geo_point)
                #				request_point = levr.geo_converter('42.35,-71.110')
                #				center_hash = geohash.encode(request_point.lat,request_point.lon,precision=6)
                #				hash_set = geohash.expand(center_hash)
                #
                #				#get keys of all corresponding deals
                #				deal_keys = []
                #				for query_hash in hash_set:
                #					q.filter('geo_hash >=',query_hash) #min bound
                #					q.filter('geo_hash <=',query_hash+"{") #max bound
                #					deal_keys.extend(q.fetch(None))
                #
                #				#batch get results. here is where we would set the number of results we want and the offset
                #				results = levr.Deal.get(deal_keys)
                #				logging.debug
                #				#define an empty "dealResults" LIST, and initialize the counter to 0
                #				#initialize isEmpty to 1
                #				isEmpty = True
                #				#iterate over the results
                #				#Want to grab deal information for each category
                #				for result in results:
                ##					logging.info('Rank: ' + str(result.rank))
                #					#break if results limit is hit
                #					isEmpty = False
                #					#trade an object for a phone-formatted dictionary
                #					deal = levr.phoneFormat(result,'list',primaryCat)
                #					#indicate that this is not a sentinel
                #					deal['isSentinel'] = False
                #					#push the whole dictionary onto a list
                #					dealResults.append(deal)
                #					#increment the counter
                ##					resultsPushed += 1
                #				###########################/OLD

                #				#if isempty is true, send back suggested searches instead
                #				if isEmpty == False:
                #					dealResults.append({"isSentinel":True})
                #
                #				#go get (all) suggested searches
                #				q = levr.EmptySetResponse.all()
                #				#sory by index
                #				q.order('index')
                #				#loop through and append to data
                #				for result in q:
                #					searchObj = {"isSentinel":False,
                #								"primaryCat":result.primary_cat,
                #								"imgURL": levr_utils.URL+"/phone/img?size=emptySet&dealID=" + enc.encrypt_key(result.key())
                #					}
                #					#push to stack
                #					dealResults.append(searchObj)
                #get notifications
                #				ninja = levr.Customer.get(uid)
                #				notifications = ninja.get_notifications()

                #add boundary
                lon = [
                    -71.13128751569184, -71.13747576487495, -71.13221920314751,
                    -71.1315606660475, -71.1309193072284, -71.1297731686955,
                    -71.12886527141396, -71.12773981063141, -71.12726203628873,
                    -71.1216289071829, -71.12121164180434, -71.10497418088163,
                    -71.1040140000405, -71.10267756839711, -71.0946922485677,
                    -71.09243243954906, -71.09227823963506, -71.0950832349529,
                    -71.097815779737, -71.11251814985596, -71.11356954283684,
                    -71.11706884229781, -71.11779512636194, -71.11965434764042,
                    -71.12212678446998, -71.12626327632834, -71.13026582412857
                ]
                lat = [
                    42.35604793867138, 42.3536306062291, 42.35301975662632,
                    42.35130590336475, 42.35025979303107, 42.34889896173047,
                    42.3474035881804, 42.34587017442897, 42.3454410032402,
                    42.34240376898205, 42.34200386027403, 42.34665152547006,
                    42.34437686280481, 42.34335156373593, 42.34544719585433,
                    42.34689842049458, 42.35112647889721, 42.35062769794382,
                    42.35071497934108, 42.35189268933054, 42.35225746246078,
                    42.35405913476999, 42.35424633071435, 42.35461863217454,
                    42.35493709975472, 42.35550741935002, 42.35597048179658
                ]

                boundary = {"lat": lat, "lon": lon}

                if primaryCat == 'all':
                    #echo back data - include boundary
                    toEcho = {
                        "success": True,
                        "data": dealResults,
                        "isEmpty": isEmpty,
                        "boundary": boundary
                    }  #,"notifications":notifications}
                else:
                    toEcho = {
                        "success": True,
                        "data": dealResults,
                        "isEmpty": isEmpty
                    }  #,"notifications":notifications}
            #***************getUserFavs************************************************
            elif action == "getUserFavs":
                '''
				Grabs all of the favorites of a user - only data to show on list
				input : uid
				output: name, description, dealValue, dealType, imgPath, businessName, primaryCat
				'''
                logging.info('getUserFavs')
                #grab inputs
                uid = enc.decrypt_key(decoded["in"]["uid"])
                logging.debug(uid)
                logging.debug(decoded["in"]["uid"])
                #grab user entity
                user = levr.Customer.get(uid)

                #grab list of favorties - list of deal keys
                favorites = user.favorites
                logging.debug(favorites)

                #batch grab favorited deals
                deals = levr.Deal.get(favorites)
                logging.debug(deals)

                #format deals for output to phone
                formatted_deals = []
                for deal in deals:
                    try:
                        formatted_deals.append(levr.phoneFormat(deal, 'list'))
                    except:
                        logging.warning(
                            'deal exists in favorites but was removed from the db'
                        )
                        logging.warning(deal)
#				formatted_deals	= [levr.phoneFormat(deal,'list') for deal in deals]

#assign formatted deals to data list that doesnt follow standards
                data = formatted_deals

                #get notifications
                notifications = user.get_notifications()

                #output
                toEcho = {
                    "success": True,
                    "data": data,
                    'notifications': notifications
                }
            #ADD FAVORITE***********************************************************
            elif action == "addFav":
                '''
				User pressed add favorite button = add favorite mapping
				input: dealID,uid,primaryCat
				output: success = bool
				'''
                logging.info('addFav')
                #get inputs
                uid = enc.decrypt_key(decoded["in"]["uid"])
                dealID = enc.decrypt_key(decoded["in"]["dealID"])

                #get user entity
                user = levr.Customer.get(uid)

                #append dealID to favorites property
                user.favorites.append(db.Key(dealID))
                logging.debug(user.favorites)
                #
                #get notifications
                notifications = user.get_notifications()

                #close entity
                user.put()

                #output
                toEcho = {"success": True, "notifications": notifications}
            #DELETE FAVORITE********************************************************
            elif action == "delFav":
                '''
				User presses delete favorite button - delete favorite mapping
				input: dealID,uid,primaryCat
				output: success = bool
				'''
                logging.info('delFav')
                #get inputs
                uid = enc.decrypt_key(decoded["in"]["uid"])
                dealID = enc.decrypt_key(decoded["in"]["dealID"])
                deal_to_delete = db.Key(dealID)
                logging.debug(deal_to_delete)

                #get user entity
                user = levr.Customer.get(uid)
                logging.debug(levr_utils.log_model_props(user))

                #grab favorites list
                favorites = user.favorites
                logging.debug(favorites)

                #generate new favorites list without requested dealID
                new_favorites = [
                    deal for deal in favorites if deal != deal_to_delete
                ]
                logging.debug(new_favorites)

                #reassign user favorites to new list
                user.favorites = new_favorites
                logging.debug(user.favorites)

                #get notifications
                notifications = user.get_notifications()

                #close entity
                user.put()

                toEcho = {"success": True, "notificaions": notifications}
            #***************getOneDeal************************************************
            elif action == "getOneDeal":
                '''
				Information to show on the deal information screen.
				input	: primaryCat,dealID
				output	: json object of all information necessary to describe deal
				'''
                logging.info('getOneDeal')
                #grab input dealID
                dealID = enc.decrypt_key(decoded["in"]["dealID"])
                primary_cat = decoded["in"]["primaryCat"]
                #fetch deal
                result = levr.Deal.get(dealID)
                #convert fetched deal into dictionary
                deal = levr.phoneFormat(result, 'deal')
                #push the primary onto the dictionary
                deal.update({"primaryCat": primary_cat})
                #echo back success!

                #				#get notifications
                #				ninja = levr.Customer.get(uid)
                #				notifications = ninja.get_notifications()
                toEcho = {
                    "success": True,
                    "data": deal
                }  #,"notificaions":notifications}

            elif action == "getMyDeals":
                '''
				returns all of the deals that were uploaded by the ninja
				input	: uid
				output	: list of deal objects
				'''
                logging.info('getMyDeals')
                uid = enc.decrypt_key(decoded["in"]["uid"])
                logging.debug("encrypted uid: " + str(decoded["in"]["uid"]))
                logging.debug("uid: " + str(uid))
                #grab all deal children of the user
                deals = levr.CustomerDeal.gql(
                    "WHERE ANCESTOR IS :1 ORDER BY date_uploaded DESC",
                    uid).fetch(None)
                logging.debug(deals)
                #format CUSTOMER deals
                data = [levr.phoneFormat(x, 'myDeals') for x in deals]
                #I believe this will just return data:None if deals is empty

                #flush their notifications
                ninja = levr.Customer.get(uid)

                #				ninja.flush_new_redeem_count()
                #				ninja.put()
                #get new notifications
                notifications = ninja.get_notifications()

                #Grab their cash out requests, if they exist
                cor_q = levr.CashOutRequest.gql(
                    "WHERE ANCESTOR IS :1 AND status=:2", uid, 'pending')
                cor = cor_q.get()
                if cor != None:
                    notifications["isPendingCashOut"] = True
                else:
                    notifications["isPendingCashOut"] = False
                notifications["pendingCashOutAmount"] = ninja.money_available
                toEcho = {
                    "success": True,
                    "data": data,
                    "notifications": notifications
                }

            elif action == "getMyStats":
                '''
				returns the user's statistics
				input	: uid
				output	: 
				'''
                logging.info('getMyStats')
                uid = enc.decrypt_key(decoded['in']['uid'])
                #get user information
                user = db.get(uid)
                #format user information
                data = user.get_stats()

                #get new notifications
                notifications = user.get_notifications()
                toEcho = {
                    "success": True,
                    "data": data,
                    "notifications": notifications
                }

            elif action == "checkRedeem":
                logging.info('checkRedeem')
                #grab corresponding deal
                uid = enc.decrypt_key(decoded['in']['uid'])
                dealID = enc.decrypt_key(decoded['in']['dealID'])

                #grab the customer
                customer = levr.Customer.get(uid)

                #new notifications?
                notifications = customer.get_notifications()
                #don't try and redeem the same deal twice. . .
                if str(dealID) in customer.redemptions:
                    toEcho = {
                        "success": False,
                        "data": {
                            "message": "You have already redeemed this deal."
                        },
                        "notifications": notifications
                    }
                else:
                    toEcho = {"success": True, "notifications": notifications}

                #!!!!!!!!REMOVE THIS WHEN CHECKING IS PUT BACK IN
#				toEcho = {"success":True,"notifications":notifications}

            elif action == "getRedeemScreen":
                logging.info('getRedeemScreen')
                #grab inputs
                dealID = enc.decrypt_key(decoded['in']['dealID'])

                #grab the deal
                deal = levr.Deal.get(dealID)

                #format the deal
                data = levr.phoneFormat(deal, 'dealsScreen')

                #echo
                toEcho = {"success": True, "data": data}

            elif action == "redeem":
                logging.info('redeem')
                #grab corresponding deal
                uid = enc.decrypt_key(decoded['in']['uid'])
                dealID = enc.decrypt_key(decoded['in']['dealID'])

                #grab the deal
                deal = levr.Deal.get(dealID)
                #grab the customer
                customer = levr.Customer.get(uid)

                #don't try and redeem the same deal twice. . .
                #				if dealID in customer.redemptions:
                #					raise Exception('Cannot redeem a deal more than once')
                #increment deal "redeemed" count by 1
                deal.count_redeemed += 1
                #add deal to "redeemed" for the customer
                customer.redemptions.append(dealID)
                ###get customer new_redemptions if they are a ninja
                notifications = customer.get_notifications()
                #update customer
                customer.put()

                #Is this a deal uploaded by a ninja? If so, do ninja things
                if type(deal) is levr.CustomerDeal:
                    #update deal ninjaStats
                    deal.gate_count = int(
                        math.floor(deal.count_redeemed /
                                   deal.gate_requirement))
                    if deal.gate_count > deal.gate_max:
                        #reset if over
                        deal.gate_count = deal.gate_max
                    #update deal.earned_total
                    difference = deal.update_earned_total()
                    #put deal
                    deal.put()
                    #get the ninja
                    ninjaKey = deal.key().parent()
                    ninja = levr.Customer.get(ninjaKey)

                    #update the ninja's earned amount
                    ninja.update_money_earned(difference)

                    #update the ninja's available amount
                    ninja.update_money_available(difference)

                    #notify the ninja of new redemptions
                    ninja.increment_new_redeem_count()

                    #echo stats
                    ninja.echo_stats()
                    deal.echo_stats()

                    #update ninja
                    ninja.put()
                else:
                    #deal is owned by a business - FOR THE FUTURE!
                    logging.info('Business!')
                    pass

                toEcho = {"success": True, "notifications": notifications}
            elif action == "cashOut":
                logging.info('cashOut')
                uid = enc.decrypt_key(decoded['in']['uid'])
                #				uid = 'ahNkZXZ-bGV2ci1wcm9kdWN0aW9ucg8LEghDdXN0b21lchiYAQw'
                #grab the ninja
                ninja = levr.Customer.get(uid)
                #delete any current cashOutRequests
                q = levr.CashOutRequest.gql(
                    'WHERE ANCESTOR IS :1 AND status=:2', ninja.key(),
                    'pending').fetch(None)
                for result in q:
                    result.delete()
                #create a new cashOut request
                cor = levr.CashOutRequest(parent=ninja)
                cor.amount = ninja.money_available
                cor.money_available_paytime = cor.amount
                #get notifications
                notifications = ninja.get_notifications()
                if cor.amount == 0:
                    toEcho = {
                        "success": False,
                        "data": {
                            "message":
                            "You need to earn something before you can cash out!",
                            "notifications": notifications
                        }
                    }
                else:
                    cor.status = 'pending'
                    cor.date_created = datetime.now()
                    cor.put()
                    toEcho = {"success": True, "notifications": notifications}

                    ## ====== SPOOF ACCEPTANCE FOR BETA TEST ====== ##

                    logging.debug(levr_utils.log_model_props(ninja))
                    logging.debug(levr_utils.log_model_props(cor))

                    #get corID
                    #get cor
                    #get the larger amount if money available at paytime is different
                    if cor.amount != cor.money_available_paytime:
                        amount = cor.money_available_paytime
                        cor.note = 'The money available at paytime was greater than when the COR was created, so the paytime balance was used.'
                    else:
                        amount = cor.amount
                    #get payment email
                    receiver_email = ninja.email

                    #set cor to "paid"
                    cor.status = "paid"
                    cor.date_paid = datetime.now()
                    cor.payKey = 'this is a pay key'

                    cor.put()

                    #for each deal, make paid_out == earned_total
                    q = levr.CustomerDeal.gql('WHERE ANCESTOR IS :1',
                                              ninja.key())
                    for deal in q:
                        deal.paid_out = deal.earned_total
                        deal.put()

                    #are number consistent?
                    logging.debug(cor.amount)
                    logging.debug(cor.money_available_paytime)
                    if cor.amount != cor.money_available_paytime:
                        #remember to encrypt the key if this is being used for anything
                        #other than just error logging
                        logging.error('PAY MISMATCH AT UID:' +
                                      ninja.key().__str__())
                        #send email here later

                    #set ninja money_available back to 0
                    ninja.money_available = 0.0

                    #increment money_paid for the customer
                    ninja.money_paid += amount

                    #update ninja
                    ninja.put()
                    logging.info('Payment completed!')
                    logging.debug(levr_utils.log_model_props(ninja))
                    logging.debug(levr_utils.log_model_props(cor))
                    #send email to the ninja confirming their cashout!
                    message = mail.EmailMessage(sender="LEVR <*****@*****.**>",
                                                subject="Levr Cash Out",
                                                to=receiver_email)
                    logging.debug(message)
                    body = 'Hey Beta Tester,\n\n'
                    body += "You submitted a request to be paid for uploading deals to the Levr platform.\n\n"
                    body += "If this were real life, this email would be letting you know that you were about to be paid via paypal an amount of $" + str(
                        amount) + ". "
                    body += "Unfortunately your reality is being simulated. "
                    body += "\n\nThanks for helping us test.\nSincerely,\nThe Levr Team"


#					#alt body for when not in beta
#					message = mail.EmailMessage(
#						sender	="LEVR <*****@*****.**>",
#						subject	="Levr Cash Out",
#						to		=receiver_email)
#					body = 'Hey '+ninja.alias+',\n\n'
#					body += "You have submitted a request to be paid for the deals that you've uploaded to Levr.\n\n"
#					body += "The amount you have requested is: $"+str(amount)+".\n\n"
#					body += "Your request is in the process of being reviewed. If accepted, we will send you an email with instructions to receive your payment via PayPal."
#					body += "\n\nSincerely,\nThe Levr Team"
#					message.body = body
#					logging.debug(body)
#					message.send()
#
            elif action == "getTargetedBusinesses":
                #get businesses that have property targeted = True
                logging.info('getTargetedBusinesses')
                businesses = levr.Business.all().filter(
                    'targeted =', True).order('-business_name').fetch(None)

                data = {'targetedBusinesses': []}

                for business in businesses:
                    data['targetedBusinesses'].append({
                        "businessName":
                        business.business_name,
                        "geoPoint":
                        str(business.geo_point),
                        "vicinity":
                        business.vicinity,
                        "businessID":
                        enc.encrypt_key(business.key())
                    })

                toEcho = {"success": True, "data": data}

            elif action == "fetchUploadURL":
                logging.info('fetchUploadURL')
                upload_url = blobstore.create_upload_url('/phone/uploadDeal')
                logging.debug(upload_url)
                toEcho = {"success": True, "data": {"url": upload_url}}

            elif action == "checkBounty":
                logging.info('fetchUploadURL')
                where = "College campuses in Boston, MA"
                what = "Offers on food, drink, clothing, and entertainment"
                toEcho = {
                    "success": True,
                    "data": {
                        "where": where,
                        "what": what
                    }
                }
            elif action == "reportDeal":
                #user reports a deal
                logging.info('reportDeal')
                uid = enc.decrypt_key(decoded['in']['uid'])
                dealID = enc.decrypt_key(decoded['in']['dealID'])

                #				uid = 'ahNkZXZ-bGV2ci1wcm9kdWN0aW9ucg8LEghDdXN0b21lchiRAQw'
                #				dealID = 'ahNkZXZ-bGV2ci1wcm9kdWN0aW9uchoLEghCdXNpbmVzcxiTAQwLEgREZWFsGJQBDA'
                #				dealID = 'ahNkZXZ-bGV2ci1wcm9kdWN0aW9uchoLEghDdXN0b21lchiSAQwLEgREZWFsGJUBDA'
                #				dateTime = enc.decrypt_key(decoded['in']['dateTime'])

                #create report Entity
                report = levr.ReportedDeal(uid=db.Key(uid),
                                           dealID=db.Key(dealID)).put()

                #get human readable info for email
                deal = levr.Deal.get(dealID)
                business = db.get(deal.businessID)
                business_name = business.business_name

                deal_text = deal.deal_text
                user = levr.Customer.get(uid)
                alias = user.display_name

                logging.debug(report)

                #send notification via email
                message = mail.EmailMessage(
                    sender="LEVR AUTOMATED <*****@*****.**>",
                    subject="New Reported Deal",
                    to="*****@*****.**")

                logging.debug(message)
                body = 'New Reported Deal\n\n'
                body += 'reporter uid: ' + str(uid) + "\n\n"
                body += 'reporter display_name: ' + str(alias) + "\n\n"
                body += 'Business name: ' + str(business_name) + "\n\n"
                body += 'Business vicinity: ' + str(business.vicinity) + "\n\n"
                body += "Deal: " + str(deal_text) + "\n\n"
                body += "dealID: " + str(dealID) + "\n\n"
                message.body = body
                logging.debug(message.body)
                message.send()

                notifications = user.get_notifications()
                toEcho = {"success": True, "notifications": notifications}
            elif action == 'ninjaHasShared':
                logging.info(action)
                uid = enc.decrypt_key(decoded['in']['uid'])
                dealID = enc.decrypt_key(decoded['in']['dealID'])

                keys = [dealID, uid]
                logging.debug(keys)
                #pull deal and user
                entities = db.get(keys)
                deal = entities[0]
                user = entities[1]

                logging.debug(
                    levr_utils.log_model_props(deal, [
                        'deal_text', 'business_name', 'gate_max',
                        'has_been_shared'
                    ]))

                deal.share_deal()
                deal.put()

                logging.debug(
                    levr_utils.log_model_props(
                        deal, ['gate_max', 'has_been_shared']))

                notifications = user.get_notifications()
                toEcho = {"success": True, "notifications": notifications}
            else:
                raise Exception('Unrecognized action')
Ejemplo n.º 31
0
	def post(self):
		#decode the input JSON and pull out the action parameter
		try:
			decoded = json.loads(self.request.body)
			action = decoded["action"]
			logging.info(action)
			try:
				uid	= enc.decrypt_key(decoded["in"]["uid"])
				user = levr.Customer.get(uid)
				logging.debug(levr_utils.log_model_props(user,['alias','email']))
			except Exception, e:
#				logging.debug(uid)
				logging.debug(e)
					
			#switch action
			#***************signup************************************************
			if action == "signup":
				logging.info('signup')
				#grab email/password from request body
				email = decoded["in"]["email"]
				alias = decoded["in"]["alias"]
				pw = decoded["in"]["pw"]
				toEcho = levr_utils.signupCustomer(email,alias,pw)
		
			#***************login*************************************************
			elif action == "login":
				logging.info('login')
			#grab email/password from request body
				email_or_owner = decoded["in"]["email_or_owner"]
				pw = decoded["in"]["pw"]
				
				toEcho = levr_utils.loginCustomer(email_or_owner,pw)
			
			#***************dealResults************************************************
			elif action == "popularItems":
				logging.info('popularItems')
				lat = decoded['in']['latitude']
				lon = decoded['in']['longitude']
				
				request_point = levr.geo_converter(str(lat)+","+str(lon))
				
				#get all deals in the area
				deals = levr_utils.get_deals_in_area(['all'],request_point)
				
				#compile a list of all of the tags
				tags = []
				for deal in deals:
					tags.extend(list(set(deal.tags)))
				tags.sort()
				logging.debug(tags)
				
				
				
				#convert list of all tags to a dict of key=tag, val=frequency
				count = {}
				for tag in tags:
#					logging.debug(tag in count)
					if tag in count:
						count[tag] += 1
					else:
						count[tag] = 1
						
				#DEBUG
				#convert dict of tag:freq into list of tuples
				tuple_list1 = []
				for key in count:
					tuple_list1.append((count[key],key))
				tuple_list1.sort()
				tuple_list1.reverse()
				logging.debug(tuple_list1)
				#/DEBUG
				
				#remove unwanted stuff
				new_count = {}
				for tag in count:
					#search occurs more than once
					if count[tag] >1:
						#tag is not a number
						if tag.isdigit() == False:
							#tag is not in blacklist
							if tag not in blacklist:
								new_count[tag] = count[tag]
					
#				logging.debug(levr_utils.log_dict(count))

				
				#convert dict of tag:freq into list of tuples
				tuple_list = []
				for key in new_count:
					tuple_list.append((new_count[key],key))
				tuple_list.sort()
				tuple_list.reverse()
				
				logging.debug(tuple_list)
#				for i in tuple_list:
#					logging.debug(i)
				
				#select only the most popular ones, and convert to list
				word_list = [x[1] for x in tuple_list]
				
				
				#if the popular items list is longer than 6, send entire list, else only send 6
				logging.debug(word_list.__len__())
				if word_list.__len__()<6:
					popularItems = word_list
				else:
					popularItems = word_list[:6]
				
				
				data = {
					'popularItems' : popularItems
					}
				toEcho = {'success': True,'data':data}
			
			elif action == "dealResults":
				logging.info('dealResults')
				logging.info(decoded['in'])
				#grab primaryCat from the request body
				primaryCat 	= decoded["in"]["primaryCat"]
					#search term
#				start 		= decoded["in"]["start"]
					#starting index of search results
					#!!!not used
				numResults 	= decoded["in"]["size"]
				geo_point	= decoded["in"]["geoPoint"]
				try:
					precision = int(decoded['in']['precision'])
				except:
					precision = 5
				
				logging.debug(numResults)
					#length of search results list
					#should be None if we want all results
				
				
				#normalize search query
				primaryCat = primaryCat.lower()
				
				###filter by location - get neighborhoods
				request_point = levr.geo_converter(geo_point)
				
				#normalize search query
				primaryCat = primaryCat.lower()
				#otherwise, search based on the tags
				tags = levr.tagger(primaryCat)
				logging.debug(tags)
				
				#batch get results. here is where we would set the number of results we want and the offset
				results = levr_utils.get_deals_in_area(tags,request_point,precision)
				
				
				
				#define an empty "dealResults" LIST, and initialize the counter to 0
				#initialize isEmpty to 1
				isEmpty = True
				dealResults = []
				#iterate over the results
				#Want to grab deal information for each category
				for result in results:
#					logging.info('Rank: ' + str(result.rank))
					#break if results limit is hit
					isEmpty = False
					#trade an object for a phone-formatted dictionary
					deal = levr.phoneFormat(result,'list',primaryCat)
					#indicate that this is not a sentinel
					deal['isSentinel'] = False
					logging.debug(result.geo_hash)
					#push the whole dictionary onto a list
					dealResults.append(deal)
					#increment the counter
#					resultsPushed += 1
				logging.debug(dealResults.__len__())
				
				##debug
#				deals = levr.Deal.all().fetch(None)
#				for d in deals:
#					logging.debug(d.geo_hash)
				
				
#				############OLD
#				#normalize search query
#				primaryCat = primaryCat.lower()
#				
#				
#				#build search query
#				q = levr.Deal.all()
#				
#				logging.debug("total number of deals: "+str(q.count()))
#				#only active deals
#				q.filter('deal_status','active')
#				#primaryCat will be mapresults to return everything
#				if primaryCat == 'all':
#					#get all deals - no filter
#					logging.debug('all')
#				else:
#					logging.debug('not all')
#					#normalize search query
#					primaryCat = primaryCat.lower()
#					#otherwise, search based on the tags
#					tags = levr.tagger(primaryCat)
#					logging.debug(tags)
#					#grab all deals where primary_cat is in tags
#					for tag in tags:
#						logging.debug('tag: '+str(tag))
#						q.filter('tags =',tag)
#				
#				###filter by location
#				request_point = levr.geo_converter(geo_point)
#				request_point = levr.geo_converter('42.35,-71.110')
#				center_hash = geohash.encode(request_point.lat,request_point.lon,precision=6)
#				hash_set = geohash.expand(center_hash)
#				
#				#get keys of all corresponding deals
#				deal_keys = []
#				for query_hash in hash_set:
#					q.filter('geo_hash >=',query_hash) #min bound
#					q.filter('geo_hash <=',query_hash+"{") #max bound
#					deal_keys.extend(q.fetch(None))
#				
#				#batch get results. here is where we would set the number of results we want and the offset
#				results = levr.Deal.get(deal_keys)
#				logging.debug
#				#define an empty "dealResults" LIST, and initialize the counter to 0
#				#initialize isEmpty to 1
#				isEmpty = True
#				#iterate over the results
#				#Want to grab deal information for each category
#				for result in results:
##					logging.info('Rank: ' + str(result.rank))
#					#break if results limit is hit
#					isEmpty = False
#					#trade an object for a phone-formatted dictionary
#					deal = levr.phoneFormat(result,'list',primaryCat)
#					#indicate that this is not a sentinel
#					deal['isSentinel'] = False
#					#push the whole dictionary onto a list
#					dealResults.append(deal)
#					#increment the counter
##					resultsPushed += 1
#				###########################/OLD


#				#if isempty is true, send back suggested searches instead
#				if isEmpty == False:
#					dealResults.append({"isSentinel":True})
#		
#				#go get (all) suggested searches
#				q = levr.EmptySetResponse.all()
#				#sory by index
#				q.order('index')
#				#loop through and append to data
#				for result in q:
#					searchObj = {"isSentinel":False,
#								"primaryCat":result.primary_cat,
#								"imgURL": levr_utils.URL+"/phone/img?size=emptySet&dealID=" + enc.encrypt_key(result.key())
#					} 
#					#push to stack
#					dealResults.append(searchObj)
				#get notifications
#				ninja = levr.Customer.get(uid)
#				notifications = ninja.get_notifications()

				#add boundary
				lon = [-71.13128751569184, -71.13747576487495, -71.13221920314751, -71.1315606660475, -71.1309193072284, -71.1297731686955, -71.12886527141396, -71.12773981063141, -71.12726203628873, -71.1216289071829, -71.12121164180434, -71.10497418088163, -71.1040140000405, -71.10267756839711, -71.0946922485677, -71.09243243954906, -71.09227823963506, -71.0950832349529, -71.097815779737, -71.11251814985596, -71.11356954283684, -71.11706884229781, -71.11779512636194, -71.11965434764042, -71.12212678446998, -71.12626327632834, -71.13026582412857]
				lat = [42.35604793867138, 42.3536306062291, 42.35301975662632, 42.35130590336475, 42.35025979303107, 42.34889896173047, 42.3474035881804, 42.34587017442897, 42.3454410032402, 42.34240376898205, 42.34200386027403, 42.34665152547006, 42.34437686280481, 42.34335156373593, 42.34544719585433, 42.34689842049458, 42.35112647889721, 42.35062769794382, 42.35071497934108, 42.35189268933054, 42.35225746246078, 42.35405913476999, 42.35424633071435, 42.35461863217454, 42.35493709975472, 42.35550741935002, 42.35597048179658]
				
				boundary = {"lat":lat,
							"lon":lon}
				
				if primaryCat == 'all':
					#echo back data - include boundary
					toEcho = {"success":True,"data":dealResults,"isEmpty":isEmpty,"boundary":boundary}#,"notifications":notifications}
				else:
					toEcho = {"success":True,"data":dealResults,"isEmpty":isEmpty}#,"notifications":notifications}
			#***************getUserFavs************************************************
			elif action == "getUserFavs":
				'''
				Grabs all of the favorites of a user - only data to show on list
				input : uid
				output: name, description, dealValue, dealType, imgPath, businessName, primaryCat
				'''
				logging.info('getUserFavs')
				#grab inputs
				uid	= enc.decrypt_key(decoded["in"]["uid"])
				logging.debug(uid)
				logging.debug(decoded["in"]["uid"])
				#grab user entity
				user	= levr.Customer.get(uid)
				
				#grab list of favorties - list of deal keys
				favorites	= user.favorites
				logging.debug(favorites)
				
				#batch grab favorited deals
				deals	= levr.Deal.get(favorites)
				logging.debug(deals)
				
				#format deals for output to phone
				formatted_deals = []
				for deal in deals:
					try:
						formatted_deals.append(levr.phoneFormat(deal,'list'))
					except:
						logging.warning('deal exists in favorites but was removed from the db')
						logging.warning(deal)
#				formatted_deals	= [levr.phoneFormat(deal,'list') for deal in deals]
				
				#assign formatted deals to data list that doesnt follow standards
				data = formatted_deals
				
				#get notifications
				notifications = user.get_notifications()
				
				#output
				toEcho = {"success":True,"data":data,'notifications':notifications}
			#ADD FAVORITE***********************************************************
			elif action == "addFav":
				'''
				User pressed add favorite button = add favorite mapping
				input: dealID,uid,primaryCat
				output: success = bool
				'''
				logging.info('addFav')
				#get inputs
				uid 		= enc.decrypt_key(decoded["in"]["uid"])
				dealID 		= enc.decrypt_key(decoded["in"]["dealID"])
				
				#get user entity
				user		= levr.Customer.get(uid)
				
				#append dealID to favorites property
				user.favorites.append(db.Key(dealID))
				logging.debug(user.favorites)
#				
				#get notifications
				notifications = user.get_notifications()
				
				#close entity
				user.put()
				
				#output
				toEcho = {"success":True,"notifications":notifications}
			#DELETE FAVORITE********************************************************
			elif action == "delFav":
				'''
				User presses delete favorite button - delete favorite mapping
				input: dealID,uid,primaryCat
				output: success = bool
				'''
				logging.info('delFav')
				#get inputs
				uid 	= enc.decrypt_key(decoded["in"]["uid"])
				dealID 	= enc.decrypt_key(decoded["in"]["dealID"])
				deal_to_delete	= db.Key(dealID)
				logging.debug(deal_to_delete)
				
				#get user entity
				user	= levr.Customer.get(uid)
				logging.debug(levr_utils.log_model_props(user))
				
				#grab favorites list
				favorites	= user.favorites
				logging.debug(favorites)
				
				#generate new favorites list without requested dealID
				new_favorites	= [deal for deal in favorites if deal != deal_to_delete]
				logging.debug(new_favorites)
				
				#reassign user favorites to new list
				user.favorites	= new_favorites
				logging.debug(user.favorites)
				
				#get notifications
				notifications = user.get_notifications()
				
				#close entity
				user.put()
				
				toEcho = {"success":True,"notificaions":notifications}
			#***************getOneDeal************************************************
			elif action == "getOneDeal":
				'''
				Information to show on the deal information screen.
				input	: primaryCat,dealID
				output	: json object of all information necessary to describe deal
				'''
				logging.info('getOneDeal')
				#grab input dealID
				dealID 		= enc.decrypt_key(decoded["in"]["dealID"])
				primary_cat = decoded["in"]["primaryCat"]
				#fetch deal
				result = levr.Deal.get(dealID)
				#convert fetched deal into dictionary
				deal = levr.phoneFormat(result,'deal')
				#push the primary onto the dictionary
				deal.update({"primaryCat":primary_cat})
				#echo back success!
				
#				#get notifications
#				ninja = levr.Customer.get(uid)
#				notifications = ninja.get_notifications()
				toEcho = {"success":True,"data":deal}#,"notificaions":notifications}

			elif action == "getMyDeals":
				'''
				returns all of the deals that were uploaded by the ninja
				input	: uid
				output	: list of deal objects
				'''
				logging.info('getMyDeals')
				uid	= enc.decrypt_key(decoded["in"]["uid"])
				logging.debug("encrypted uid: "+str(decoded["in"]["uid"]))
				logging.debug("uid: "+str(uid))
				#grab all deal children of the user
				deals = levr.CustomerDeal.gql("WHERE ANCESTOR IS :1 ORDER BY date_uploaded DESC",uid).fetch(None)
				logging.debug(deals)
				#format CUSTOMER deals
				data = [levr.phoneFormat(x,'myDeals') for x in deals]
				#I believe this will just return data:None if deals is empty
				
				#flush their notifications
				ninja = levr.Customer.get(uid)
				
#				ninja.flush_new_redeem_count()
#				ninja.put()
				#get new notifications
				notifications = ninja.get_notifications()
				
				#Grab their cash out requests, if they exist
				cor_q = levr.CashOutRequest.gql("WHERE ANCESTOR IS :1 AND status=:2",uid,'pending')
				cor = cor_q.get()
				if cor != None:
					notifications["isPendingCashOut"] = True
				else:
					notifications["isPendingCashOut"] = False
				notifications["pendingCashOutAmount"] = ninja.money_available
				toEcho = {"success":True,"data":data,"notifications":notifications}
				
			elif action == "getMyStats":
				'''
				returns the user's statistics
				input	: uid
				output	: 
				'''
				logging.info('getMyStats')
				uid = enc.decrypt_key(decoded['in']['uid'])
				#get user information
				user = db.get(uid)
				#format user information
				data = user.get_stats()
				
				#get new notifications
				notifications = user.get_notifications()
				toEcho = {"success":True,"data":data,"notifications":notifications}
				
			elif action == "checkRedeem":
				logging.info('checkRedeem')
				#grab corresponding deal
				uid 	= enc.decrypt_key(decoded['in']['uid'])
				dealID 	= enc.decrypt_key(decoded['in']['dealID'])
				
				#grab the customer
				customer = levr.Customer.get(uid)
				
				#new notifications?
				notifications = customer.get_notifications()
				#don't try and redeem the same deal twice. . .
				if str(dealID) in customer.redemptions:
					toEcho = {"success":False,"data":{"message":"You have already redeemed this deal."},"notifications":notifications}
				else:
					toEcho = {"success":True,"notifications":notifications}
				
				#!!!!!!!!REMOVE THIS WHEN CHECKING IS PUT BACK IN	
#				toEcho = {"success":True,"notifications":notifications}
				
			elif action == "getRedeemScreen":
				logging.info('getRedeemScreen')
				#grab inputs
				dealID 	= enc.decrypt_key(decoded['in']['dealID'])
				
				#grab the deal
				deal = levr.Deal.get(dealID)
				
				#format the deal
				data = levr.phoneFormat(deal,'dealsScreen')
				
				#echo
				toEcho = {"success":True,"data":data}
			
			elif action == "redeem":
				logging.info('redeem')
				#grab corresponding deal
				uid 	= enc.decrypt_key(decoded['in']['uid'])
				dealID 	= enc.decrypt_key(decoded['in']['dealID'])
				
				#grab the deal
				deal = levr.Deal.get(dealID)
				#grab the customer
				customer = levr.Customer.get(uid)
				
				#don't try and redeem the same deal twice. . .
#				if dealID in customer.redemptions:
#					raise Exception('Cannot redeem a deal more than once')
				#increment deal "redeemed" count by 1
				deal.count_redeemed += 1
				#add deal to "redeemed" for the customer
				customer.redemptions.append(dealID)
				###get customer new_redemptions if they are a ninja
				notifications = customer.get_notifications()
				#update customer
				customer.put()
				
				#Is this a deal uploaded by a ninja? If so, do ninja things
				if type(deal) is levr.CustomerDeal:
					#update deal ninjaStats
					deal.gate_count = int(math.floor(deal.count_redeemed / deal.gate_requirement))
					if deal.gate_count > deal.gate_max:
						#reset if over
						deal.gate_count = deal.gate_max
					#update deal.earned_total
					difference = deal.update_earned_total()
					#put deal
					deal.put()
					#get the ninja
					ninjaKey = deal.key().parent()
					ninja = levr.Customer.get(ninjaKey)
					
					#update the ninja's earned amount
					ninja.update_money_earned(difference)
					
					#update the ninja's available amount
					ninja.update_money_available(difference)
					
					#notify the ninja of new redemptions
					ninja.increment_new_redeem_count()
					
					#echo stats
					ninja.echo_stats()
					deal.echo_stats()

					#update ninja
					ninja.put()
				else:
					#deal is owned by a business - FOR THE FUTURE!
					logging.info('Business!')
					pass	
			
				toEcho = {"success":True,"notifications":notifications}
			elif action == "cashOut":
				logging.info('cashOut')
				uid = enc.decrypt_key(decoded['in']['uid'])
#				uid = 'ahNkZXZ-bGV2ci1wcm9kdWN0aW9ucg8LEghDdXN0b21lchiYAQw'
				#grab the ninja
				ninja = levr.Customer.get(uid)
				#delete any current cashOutRequests
				q = levr.CashOutRequest.gql('WHERE ANCESTOR IS :1 AND status=:2',ninja.key(),'pending').fetch(None)
				for result in q:
					result.delete()
				#create a new cashOut request
				cor = levr.CashOutRequest(parent=ninja)
				cor.amount = ninja.money_available
				cor.money_available_paytime = cor.amount
				#get notifications
				notifications = ninja.get_notifications()
				if cor.amount == 0:
					toEcho = {"success":False,"data":{"message":"You need to earn something before you can cash out!","notifications":notifications}}
				else:
					cor.status = 'pending'
					cor.date_created = datetime.now()
					cor.put()
					toEcho = {"success":True,"notifications":notifications}
				
				
				
				
				
				
					## ====== SPOOF ACCEPTANCE FOR BETA TEST ====== ##
				
				
				
				
				
					logging.debug(levr_utils.log_model_props(ninja))
					logging.debug(levr_utils.log_model_props(cor))
					
					#get corID
					#get cor
					#get the larger amount if money available at paytime is different
					if cor.amount != cor.money_available_paytime:
						amount = cor.money_available_paytime
						cor.note = 'The money available at paytime was greater than when the COR was created, so the paytime balance was used.'
					else:
						amount = cor.amount
					#get payment email
					receiver_email = ninja.email
				
					#set cor to "paid"
					cor.status = "paid"
					cor.date_paid = datetime.now()
					cor.payKey = 'this is a pay key'
				
					cor.put()
				
					#for each deal, make paid_out == earned_total
					q = levr.CustomerDeal.gql('WHERE ANCESTOR IS :1',ninja.key())
					for deal in q:
						deal.paid_out = deal.earned_total
						deal.put()
				
					#are number consistent?
					logging.debug(cor.amount)
					logging.debug(cor.money_available_paytime)
					if cor.amount != cor.money_available_paytime:
						#remember to encrypt the key if this is being used for anything
						#other than just error logging
						logging.error('PAY MISMATCH AT UID:' + ninja.key().__str__())
						#send email here later
				
					#set ninja money_available back to 0
					ninja.money_available = 0.0
				
					#increment money_paid for the customer
					ninja.money_paid += amount
					
					#update ninja
					ninja.put()
					logging.info('Payment completed!')
					logging.debug(levr_utils.log_model_props(ninja))
					logging.debug(levr_utils.log_model_props(cor))
					#send email to the ninja confirming their cashout!
					message = mail.EmailMessage(
						sender	="LEVR <*****@*****.**>",
						subject	="Levr Cash Out",
						to		=receiver_email)
					logging.debug(message)
					body = 'Hey Beta Tester,\n\n'
					body += "You submitted a request to be paid for uploading deals to the Levr platform.\n\n"
					body += "If this were real life, this email would be letting you know that you were about to be paid via paypal an amount of $"+str(amount)+". "
					body += "Unfortunately your reality is being simulated. "
					body += "\n\nThanks for helping us test.\nSincerely,\nThe Levr Team"
					
#					#alt body for when not in beta
#					message = mail.EmailMessage(
#						sender	="LEVR <*****@*****.**>",
#						subject	="Levr Cash Out",
#						to		=receiver_email)
#					body = 'Hey '+ninja.alias+',\n\n'
#					body += "You have submitted a request to be paid for the deals that you've uploaded to Levr.\n\n"
#					body += "The amount you have requested is: $"+str(amount)+".\n\n"
#					body += "Your request is in the process of being reviewed. If accepted, we will send you an email with instructions to receive your payment via PayPal."
#					body += "\n\nSincerely,\nThe Levr Team"
#					message.body = body
#					logging.debug(body)
#					message.send()
#				
			elif action == "getTargetedBusinesses":
				#get businesses that have property targeted = True
				logging.info('getTargetedBusinesses')
				businesses = levr.Business.all().filter('targeted =',True).order('-business_name').fetch(None)
				
				data = {
					'targetedBusinesses':[]
					}
				
				for business in businesses:
					data['targetedBusinesses'].append({
						"businessName"	: business.business_name,
						"geoPoint"		: str(business.geo_point),
						"vicinity"		: business.vicinity,
						"businessID"	: enc.encrypt_key(business.key())
					})
				
				toEcho = {"success":True,"data":data}
			
			elif action == "fetchUploadURL":
				logging.info('fetchUploadURL')
				upload_url = blobstore.create_upload_url('/phone/uploadDeal')
				logging.debug(upload_url)
				toEcho = {"success":True, "data":{"url":upload_url}}

			elif action == "checkBounty":
				logging.info('fetchUploadURL')
				where = "College campuses in Boston, MA"
				what = "Offers on food, drink, clothing, and entertainment"
				toEcho = {"success":True,"data":{"where":where,"what":what}}
			elif action == "reportDeal":
				#user reports a deal
				logging.info('reportDeal')
				uid = enc.decrypt_key(decoded['in']['uid'])
				dealID = enc.decrypt_key(decoded['in']['dealID'])
				
#				uid = 'ahNkZXZ-bGV2ci1wcm9kdWN0aW9ucg8LEghDdXN0b21lchiRAQw'
#				dealID = 'ahNkZXZ-bGV2ci1wcm9kdWN0aW9uchoLEghCdXNpbmVzcxiTAQwLEgREZWFsGJQBDA'
#				dealID = 'ahNkZXZ-bGV2ci1wcm9kdWN0aW9uchoLEghDdXN0b21lchiSAQwLEgREZWFsGJUBDA'
#				dateTime = enc.decrypt_key(decoded['in']['dateTime'])

				#create report Entity
				report = levr.ReportedDeal(
										uid = db.Key(uid),
										dealID = db.Key(dealID)
										).put()
				
				#get human readable info for email
				deal = levr.Deal.get(dealID)
				business_name = deal.business_name
				logging.debug(business_name)
				
				if deal.deal_type == "single":
					deal_text = deal.deal_text
				else:
					deal_text = deal.deal_text +" with purchase of "+deal.secondary_name
				
				user = levr.Customer.get(uid)
				alias = user.alias
				
				deal_class = str(deal.class_name())
				if deal_class == 'CustomerDeal':
					deal_kind = "Ninja Deal"
				elif deal_class == 'Deal':
					deal_kind = "Business Deal"
				else:
					raise ValueError('deal class_name not recognized')
				
				logging.debug(report)
				
				#send notification via email
				message = mail.EmailMessage(
					sender	="LEVR AUTOMATED <*****@*****.**>",
					subject	="New Reported Deal",
					to		="*****@*****.**")
				
				logging.debug(message)
				body = 'New Reported Deal\n\n'
				body += 'reporter uid: '  +str(uid)+"\n\n"
				body += 'reporter alias: ' +str(alias)+"\n\n"
				body += 'Business name: '+str(business_name)+"\n\n"
				body += "Deal: "+str(deal_text)+"\n\n"
				body += "Deal Kind: "+deal_kind+"\n\n"
				body += "dealID: "+str(dealID)+"\n\n"
				message.body = body
				logging.debug(message.body)
				message.send()
				
				notifications = user.get_notifications()
				toEcho = {"success":True,"notifications":notifications}
			elif action == 'ninjaHasShared':
				logging.info(action)
				uid = enc.decrypt_key(decoded['in']['uid'])
				dealID = enc.decrypt_key(decoded['in']['dealID'])
				
				
				keys = [dealID,uid]
				logging.debug(keys)
				#pull deal and user
				entities = db.get(keys)
				deal = entities[0]
				user = entities[1]
				
				logging.debug(levr_utils.log_model_props(deal,['deal_text','business_name','gate_max','has_been_shared']))
				
				deal.share_deal()
				deal.put()
				
				logging.debug(levr_utils.log_model_props(deal,['gate_max','has_been_shared']))

				
				notifications = user.get_notifications()
				toEcho = {"success":True,"notifications":notifications}
			else:
				raise Exception('Unrecognized action')
Ejemplo n.º 32
0
	def get(self):
		
		e = levr.Customer.all().filter('email','*****@*****.**').get()
		ethan = enc.encrypt_key(e.key())
		p = levr.Customer.all().filter('email','*****@*****.**').get()
		pat = enc.encrypt_key(p.key())
		a = levr.Customer.all().filter('email','*****@*****.**').get()
		alonso = enc.encrypt_key(a.key())
		n = levr.Customer.all().filter('email','*****@*****.**').get()
		ninja = enc.encrypt_key(n.key())
		
		
		
		url = '\'http://0.0.0.0:8080/api'
		
		
		ethan_url = url+'/user/'+ethan+'\' | python -mjson.tool'
		pat_url = url+'/user/'+pat+'\' | python -mjson.tool'
		alonso_url = url+'/user/'+alonso+'\' | python -mjson.tool'
		ninja_url = url+'/user/'+ninja+'\' | python -mjson.tool'
		
		
		levr_token = db.get(enc.decrypt_key(ethan)).levr_token
		self.response.out.headers['Content-Type'] = 'text/plain'
		self.response.out.write('LEVR TOKEN:\n\n')
		self.response.out.write(levr_token)
		self.response.out.write('\n\n\nFor ethan:\n\n')
		self.response.out.write(ethan)
		self.response.out.write('\n\n')
		self.response.out.write('curl '+ethan_url)
		
		self.response.out.write('\n\n\nFor pat:\n\n')
		self.response.out.write(pat)
		self.response.out.write('\n\n')
		self.response.out.write('curl '+pat_url)
		
		self.response.out.write('\n\n\n<b>For alonso: </b>\n\n')
		self.response.out.write(alonso)
		self.response.out.write('\n\n')
		self.response.out.write('curl '+alonso_url)
		
		self.response.out.write('\n\n\n<b>For ninja: </b>\n\n')
		self.response.out.write(ninja)
		self.response.out.write('\n\n')
		self.response.out.write('curl '+ninja_url)
		
		d = levr.Deal.all().ancestor(db.Key(enc.decrypt_key(ethan))).get()
		if d:
			deal = enc.encrypt_key(d.key())
			deal_url = url+'/deal/'+deal+'\' | python -mjson.tool'
		
			self.response.out.write('\n\n\n<b>For deal stuff: </b>\n\n')
			self.response.out.write(deal)
			self.response.out.write('\n\n')
	#		self.response.out.write('\n\n')
			self.response.out.write('curl '+deal_url)
		
#		projection = None
		projection = [
					'alias',
					'new_notifications',
					'first_name',
					'last_name',
					'karma',
					'level',
					'display_name',
					'followers',
					
					'foursquare_id',
					'foursquare_token',
					'foursquare_connected',
					'foursquare_friends',
					
					'twitter_id',
					'twitter_token',
					'twitter_token_secret',
					'twitter_screen_name',
					'twitter_connected',
					'twitter_friends_by_sn',
					'twitter_friends_by_id',
					
					'facebook_connected',
					'facebook_token',
					'facebook_id',
					'facebook_friends',
					
					'email_friends',
					
					'favorites',
					'upvotes',
					'downvotes',
					]
		deal_projection = [
						'upvotes',
						'downvotes',
						'karma',
						'geo_point',
						'geo_hash'
						]
		self.response.out.write('\n\n\n Ethan')
		self.response.out.write(levr.log_model_props(e,projection))
		self.response.out.write('\n PAT')
		self.response.out.write(levr.log_model_props(p,projection))
		self.response.out.write('\n ALONSO')
		self.response.out.write(levr.log_model_props(a,projection))
		self.response.out.write('\nDEAL')
		if d: self.response.out.write(levr.log_model_props(d,deal_projection))
		self.response.out.write('\n\n')
		notifications = levr.Notification.all().fetch(None)
		for n in notifications:
			self.response.out.write(levr.log_model_props(n))
Ejemplo n.º 33
0
	def post(self):
		try:
			logging.info('uploadDeal')
			uid	= enc.decrypt_key(self.request.get('uid'))
			user = levr.Customer.get(uid)
			logging.debug(levr_utils.log_model_props(user,['alias','email']))
			logging.debug(self.request.params)
			#make sure than an image is uploaded
			logging.debug(self.get_uploads())
			if self.get_uploads(): #will this work?
				upload	= self.get_uploads()[0]
				blob_key= upload.key()
				img_key = blob_key
			else:
				raise Exception('Image was not uploaded')
			
			
			#screen for businessID to determine which mode of upload we are receiving
			if self.request.get('businessID'):
				logging.debug('targeted business')
				#we are on iphone
				origin = 'phone_existing_business'
				params = {
					'uid'				: self.request.get('uid'),
					'business'			: self.request.get('businessID'),
					'deal_description'	: self.request.get('deal_description'),
					'deal_line1'		: self.request.get('deal_line1'),
					'distance'			: self.request.get('distance'), #is -1 if unknown = double
					'img_key'			: img_key
					}
				
#				(share_url,deal_entity) = levr_utils.dealCreate(params,'phone_existing_business')
			else:
				logging.debug('untargeted business')
				#we are on android
				origin = 'phone_new_business'
				params = {
					'uid'				: self.request.get('uid'),
					'business_name'		: self.request.get('businessName'),
					'geo_point'			: self.request.get('geoPoint'),
					'vicinity'			: self.request.get('vicinity'),
					'types'				: self.request.get('types'),
					'deal_description'	: self.request.get('deal_description'),
					'deal_line1'		: self.request.get('deal_line1'),
					'distance'			: self.request.get('distance'), #is -1 if unknown = double
					'img_key'			: img_key
					}
			
			
			
			#create the deal using the origin specified
			(share_url,deal_entity) = levr_utils.dealCreate(params,origin)
			
			#grab deal information for sending back to phone
			deal = levr.phoneFormat(deal_entity,'list')
			
			
			#Return Info..
			toEcho = {"success":True,"data":{"shareURL":share_url,"deal":deal}}
			logging.debug(levr_utils.log_dict(toEcho))
			self.response.out.write(json.dumps(toEcho))
		except:
			levr.log_error(self.request.body)
			toEcho = {"success":False}#,"data":{"shareURL":share_url}}
			self.response.out.write(json.dumps(toEcho))
Ejemplo n.º 34
0
def dealCreate(params,origin,upload_flag=True):
	'''pass in "self"'''
	logging.debug('DEAL CREATE')
	
	logging.debug("origin: "+str(origin))
	logging.debug(log_dict(params))
	
	
	logging.debug("image was uploaded: "+str(upload_flag))
	#init tags list for deal
	tags = []
	
	#business information - never create business unless old phone
		#just want to get tags to store on deal
	#get deal information
	#create deals with appropriate owners
	
	'''

	
	#####merchant_edit
		params = {
				'uid'			#uid is businessOwner
				'business'		#businessID
				'deal'			#dealID
				'deal_description'
				'deal_line1'
				'deal_line2'
				}
		!!! check for uploaded image !!!
		

	#####merchant_create
		params = {
				'uid'			#uid is businessOwner
				'business'
				'deal_line1'
				'deal_line2' 	#optional
				'deal_description'
				'img_key'
				}
		
	#####phone_existing_business
		params = {
				'uid' 			#uid is ninja
				'business' 
				'deal_description'
				'deal_line1'
				!!! no deal_line2 !!!
				}
	#####phone_new_business
		params = {
				'uid'			#uid is ninja
				'business_name'
				'geo_point'
				'vicinity'
				'types'
				'deal_description'
				'deal_line1'
				}
	#####admin_review
		params = {
				'uid'		#uid is ninja
				'deal'		#deal id
				'business'	#business id
				'deal_line1'
				'deal_line2'
				'deal_description'
				'tags'
				'end date'
				!!! other stuff !!!
				}
	'''
	
	
	#==== deal information ====#
	
	
	#==== business stuff ====#
	if origin == 'phone_new_business':
		#The business to which a deal is being uploaded is not targeted
		logging.debug('origin is phone, new business being added')
		
		
		#business name
		if 'business_name' in params:
			business_name = params['business_name']
			logging.debug("business name: "+str(business_name))
		else:
			raise KeyError('business_name not in params')
		#geo point
		
		if 'geo_point' in params:
			geo_point = params['geo_point']
			geo_point = levr.geo_converter(geo_point)
			logging.debug("geo point: "+str(geo_point))
			#create geohash from geopoint
			geo_hash = geohash.encode(geo_point.lat,geo_point.lon)
			logging.info(geo_hash)
		else:
			raise KeyError('geo_point not in params')
		
		#vicinity
		if 'vicinity' in params:
			vicinity = params['vicinity']
			logging.debug("vicinity: "+str(vicinity))
		else:
			raise KeyError('vicinity not in params')
		
		#types
		if 'types' in params:
			types = params['types']
			logging.debug('start types')
			logging.debug(types)
			logging.debug(type(types))
			types = levr.tagger(types)
			logging.debug(types)
			logging.debug('end types')
		else:
			raise KeyError('types not in params')
		#check if business exists - get businessID
#		business= levr.Business.gql("WHERE business_name=:1 and geo_point=:2", business_name, geo_point).get()
		business = levr.Business.all().filter('business_name =',business_name).filter('vicinity =',vicinity).get()
		logging.debug('start business info')
		logging.debug(log_model_props(business))
		logging.debug('end business info')
		
		if not business:
			logging.debug('business doesnt exist')
			#if a business doesn't exist in db, then create a new one
			business = levr.Business()
			
			
			
			
			#add data to the new business
			business.business_name 	= business_name
			business.vicinity 		= vicinity
			business.geo_point		= geo_point
			business.types			= types
			business.geo_hash		= geo_hash
			
			logging.debug(log_model_props(business))
			#put business
			business.put()
			
			
		else:
			logging.debug('business exists')
			#business exists- grab its tags
			logging.debug(geo_hash)
		
		#grab the businesses tags
		tags.extend(business.create_tags())
		#get businessID - not encrypted - from database
		businessID = business.key()
		logging.debug("businessID: "+str(businessID))
		
		#Create tags
		
		logging.debug('-------------------------------------------')
		logging.debug(tags)
	else:
		#BusinessID was passed, grab the business
		logging.debug('not oldphoone')
		
		if 'business' in params:
			businessID = params['business']
			businessID	= enc.decrypt_key(businessID)
			businessID	= db.Key(businessID)
			business	= levr.Business.get(businessID)
		else:
			raise KeyError('business not passed in params')
		#get the tags from the business
		tags.extend(business.create_tags())
		
		#grab all the other information that needs to go into the deals
		business_name 	= business.business_name
		geo_point		= business.geo_point
		vicinity		= business.vicinity
		geo_hash		= business.geo_hash
		
		logging.debug(log_model_props(business))
		

	logging.debug('!!!!!')
	#====Deal Information Lines ====#
	#deal line 1
	if 'deal_line1' in params:
		deal_text	= params['deal_line1']
		logging.debug(deal_text)
		tags.extend(levr.tagger(deal_text))
		logging.info(tags)
	else:
		raise KeyError('deal_line1 not passed in params')
	
	#deal line 2
	if origin != 'phone_existing_business' and origin != 'phone_new_business':
		if 'deal_line2' in params:
			secondary_name = params['deal_line2']
		else:
			secondary_name = False
		logging.debug(secondary_name)
		if secondary_name:
			#deal is bundled
			logging.debug('deal is bundled')
			tags.extend(levr.tagger(secondary_name))
			logging.info(tags)
			deal_type = 'bundle'
		else:
			#deal is not bundled
			'deal is NOT bundled'
			deal_type = 'single'
	else:
		#phone uploaded deals do not pass deal_line2
		deal_type = 'single'
	
	#description
	if 'deal_description' in params:
		description = params['deal_description']
		#truncate description to a length of 500 chars
		logging.debug(description.__len__())
		description = description[:500]
		logging.debug(description)
		tags.extend(levr.tagger(description))
		logging.info(tags)
	else:
		raise KeyError('deal_description not passed in params')
	
	
	
	
	#==== create the deal entity ====#
	if origin	== 'merchant_create':
		#web deals get active status and are the child of the owner
		ownerID = params['uid']
		ownerID = enc.decrypt_key(ownerID)
		
		deal = levr.Deal(parent = db.Key(ownerID))
		deal.is_exclusive		= True

	elif origin	=='merchant_edit':
		dealID	= params['deal']
		dealID	= enc.decrypt_key(dealID)
		deal	= levr.Deal.get(dealID)

	elif origin	=='phone_existing_business' or origin == 'phone_new_business':
		#phone deals are the child of a ninja
		logging.debug('STOP!')
		uid = enc.decrypt_key(params['uid'])

		deal = levr.CustomerDeal(parent = db.Key(uid))
		deal.is_exclusive		= False
		
		
		deal.date_end			= datetime.now() + timedelta(days=7)

	elif origin == 'admin_review':
		#deal has already been uploaded by ninja - rewriting info that has been reviewed
		dealID = enc.decrypt_key(params['deal'])
		deal = levr.CustomerDeal.get(db.Key(dealID))
		deal.been_reviewed		= True
		deal.date_start			= datetime.now()
		days_active				= int(params['days_active'])
		deal.date_end			= datetime.now() + timedelta(days=days_active)
		
		new_tags = params['extra_tags']
		tags.extend(levr.tagger(new_tags))
		logging.debug('!!!!!!!!!!!!')
		logging.debug(tags)
	
	
	#==== Link deal to blobstore image ====#
	if upload_flag == True:
		#an image has been uploaded, and the blob needs to be tied to the deal
		logging.debug('image uploaded')
		if origin == 'merchant_edit' or origin == 'admin_review':
			#an image was uploaded, so remove the old one.
			blob = deal.img
			blob.delete()
		#if an image has been uploaded, add it to the deal. otherwise do nothing.
		#assumes that if an image already exists, that it the old one has been deleted elsewhere
		blob_key = params['img_key']
		deal.img= blob_key
	else:
		#an image was not uploaded. do nothing
		logging.debug('image not uploaded')
	
	
	
	
	
	#add the data
	deal.deal_text 			= deal_text
	deal.deal_type			= deal_type
	deal.description 		= description
	deal.tags				= list(set(tags)) #list->set->list removes duplicates
	deal.business_name		= business_name
	deal.businessID			= businessID.__str__()
	deal.vicinity			= vicinity
	deal.geo_point			= geo_point
	logging.debug(geo_hash)
	deal.geo_hash			= geo_hash
	
	#secondary_name
	if deal_type == 'bundle':
		deal.secondary_name = secondary_name
	
	
	
	#put the deal
	deal.put()
	
	#dealput is the deal key i.e. dealID
	logging.debug(log_model_props(deal))
	logging.debug(log_model_props(business))
	
	share_url = create_share_url(deal)
	
	if origin == 'phone_existing_business' or origin =='phone_new_business':
		#needs share url and dealID
		return share_url,deal
	else:
		#return share url
		return share_url
Ejemplo n.º 35
0
	def post(self):
		try:
			logging.debug(self.request.headers)
			logging.debug(self.request.body)
			logging.debug(self.request.params)
			
			#check login
			headerData = levr_utils.loginCheck(self, True)
			
			#get the owner information
			ownerID = headerData['ownerID']
			ownerID = enc.decrypt_key(ownerID)
			ownerID = db.Key(ownerID)
			owner = levr.BusinessOwner.get(ownerID)
			logging.debug(owner)
			
			password = enc.encrypt_password(self.request.get('old_password'))
			mode = self.request.get('change')
			logging.debug(owner.pw == password)
			if owner.pw == password:
				
				#password is correct
				
				if mode == 'email':
					#user is changing their email
					
					email			= self.request.get('new_email')
					confirm_email	= self.request.get('confirm_new_email')
					if email == confirm_email:
						logging.debug(email)
						#emails match - change owner email
						owner.email = email
						owner.put()
						self.redirect('/merchants/myAccount?success=true')
					else:
						#get the business
						business = owner.businesses.get()#TODO: this will be multiple businesses later
						
						template_values = {
						'owner'		: owner,
						'business'	: business,
						'mode'		: mode, #which form to show
						'error'		: 'confirm_new_email'
						}
						logging.debug(template_values)
						#password is incorrect
						template = jinja_environment.get_template('templates/editAccount.html')
						self.response.out.write(template.render(template_values))
					
				elif mode == 'password':
					#user is changing their password
					new_password		= self.request.get('new_password')
					confirm_new_password= self.request.get('confirm_new_password')
					
					if new_password == confirm_new_password:
						logging.debug(new_password)
						#passwords match - change owner password
						owner.pw = new_password
						owner.put()
						self.redirect('/merchants/myAccount?success=true')
					else:
						#new passwords do not match
						#get the business
						business = owner.businesses.get()#TODO: this will be multiple businesses later
						
						template_values = {
						'owner'		: owner,
						'business'	: business,
						'mode'		: mode, #which form to show
						'error'		: 'confirm_new_password'
						}
				
						#password is incorrect
						template = jinja_environment.get_template('templates/editAccount.html')
						self.response.out.write(template.render(template_values))
				else:
					#mode not recognized
					logging.error('mode not recognized')
			else:
				#old password is incorrect
				#get the business
				business = owner.businesses.get()#TODO: this will be multiple businesses later
				
				template_values = {
				'owner'		: owner,
				'business'	: business,
				'mode'		: mode, #which form to show
				'error'		: 'old_password'
				}
				
				logging.debug(template_values)
				template = jinja_environment.get_template('templates/editAccount.html')
				self.response.out.write(template.render(template_values))
		except:
			levr.log_error(self.request.headers)