def get(self): mail=self.request.get('mail') name=self.request.get('name') type=self.request.get('type') hoursToAdd=self.request.get('hourstoadd') user = User.query(User.mail == mail).get() if not user: self.error(403) self.response.write('No user - access denied') return customer=Customer.query(Customer.name==name, Customer.user==user.mail).get() if not customer: self.error(402) self.response.write('no customer') return if type== 'manager': Customer.updateCustomerManagerHours(mail, name, int(hoursToAdd)) elif type== 'worker': Customer.updateCustomerWorkerHours(mail, name, int(hoursToAdd)) else: self.error(402) self.response.write('error') return self.response.write(json.dumps({"status": "OK"}))
def PaBlacklistCustomer(self, pKey): #logging.debug("PA Blacklisting Customer: " + str(pKey)) tCustomer = Customer() tCustomerHandler = CustomerHandler() try: tCustomer = tCustomerHandler.GetCustomerByKey(pKey) tCustomer.customerIsPaBlacklisted = True tCustomer.put() tIpList = tCustomer.customerIpAddresses #logging.debug("Customer IPs: " + str(tIpList)) tUniqueIps = set(tIpList) tUniqueIps = list(tUniqueIps) ip = IpInfo() for tIp in tUniqueIps: #logging.debug("Blacklisting IP: " + str(tIp)) tIps = IpInfo().all() tIps.filter("ip", tIp) tIpModels = tIps.fetch(100) for ip in tIpModels: ip.ipIsPaBlacklisted = True ip.put() return True except: return False
def on_post(self, req, resp): data = json.loads(req.stream.read()) dob = datetime.strptime(data['dob'], '%a %b %d %Y %H:%M:%S %Z%z') customer = CustomerSchema(name=data['name'], dob=dob) self.session.add(customer) self.session.commit() resp.body = json.dumps(customer.to_json(), ensure_ascii=False)
def get(self): mail=self.request.get('mail') name=self.request.get('name') newname=self.request.get('newname') address=self.request.get('address') phone=self.request.get('phone') email=self.request.get('email') field1=self.request.get('field1') field2=self.request.get('field2') field3=self.request.get('field3') field4=self.request.get('field4') field5=self.request.get('field5') field6=self.request.get('field6') user = User.query(User.mail == mail).get() if not user: self.error(403) self.response.write('No user - access denied') return customer=Customer.query(Customer.name==name, Customer.user==user.mail).get() if not customer: self.error(402) self.response.write('no customer') return Customer.updateCustomer(mail, name, newname, address, phone, email, field1, field2, field3, field4, field5, field6) self.response.write(json.dumps({"status": "OK"}))
def on_search_clicked(self, button): """ Search button event. Fills every field with the data on the database for the given user id. """ self.model.clear() costumer = Customer(self.search_entry.get_text( )) # New costumer object with the user id on search_entry costumer_list = costumer.get_customer() # Gets the database data if costumer_list == []: #self.validation_label.set_markup("<span color='red'>No existe ese usuario</span>") '''''' else: #self.validation_label.set_text("") for item in costumer_list: self.model.append(item) purchase = Purchase(self.search_entry.get_text( )) # New purchase object with the user id on search_entry if purchase.check_purchase(): #self.validation_label.set_text("") purchases = purchase.get_purchase_by_dni( ) # Gets the database data for item in purchases: self.purchase_model.append( item) # Appends the list to the Gtk.ListStore model else: #self.validation_label.set_markup("<span color='red'>No hay productos</span>") ''''''
def post(self): '''CREATE a new Product in the database''' data = CustomerResource.parser.parse_args() customer = Customer(data['first_name'], data['last_name'], data['address']) customer.save_to_db() return customer.json()
def ProcessChargeback(self, pArgumentDic): tArgumentDic = {} tArgumentDic = pArgumentDic tCustomer = Customer() tCustomerHandler = CustomerHandler() if (tArgumentDic.has_key('payer_id')): tCustomer = tCustomerHandler.GetCustomerByPpid( tArgumentDic['payer_id'])[0] tSuccess = tCustomerHandler.PaBlacklistCustomer(str(tCustomer.key())) try: tPaypalEmail = tCustomer.customerEmail #logging.debug("Adding Chargeback Email for " + tPaypalEmail) taskqueue.add(url="/emailchargeback", countdown=1, params={"email": tPaypalEmail}) except: logging.debug("Failure Queueing Chargeback Email") if (tSuccess): logging.debug("Successfully PA Blacklisted " + str(tArgumentDic['payer_id']) + " due to Chargeback") else: logging.debug("Failure PA Blacklisting " + str(tArgumentDic['payer_id']))
def on_ticket_clicked(self, button): from reportlab.platypus import Table from reportlab.platypus import SimpleDocTemplate from reportlab.lib.pagesizes import A4 from reportlab.lib import colors script = [] table_header = [["Nombre", "Apellidos", "DNI"]] table = Table(table_header) table.setStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]) script.append(table) costumer = Customer(self.search_entry.get_text( )) # New costumer object with the user id on search_entry costumer_list = costumer.get_customer() # Gets the database data if costumer_list == []: #self.validation_label.set_markup("<span color='red'>No existe ese usuario</span>") '''''' else: table = Table(costumer_list) table.setStyle([('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black) ]) script.append(table) #creacion del archivo pdf doc = SimpleDocTemplate("cliente.pdf", pagesize=A4, showBoundary=1) doc.build(script)
def delete(self, book_id=None): #delete single book if book_id: #if book not found will cause an error try: book = ndb.Key(urlsafe=book_id).get() #make sure is book assert Book.is_book(book) #remove the book from customer's checked_out #list, if the book is checked out if book.checkedIn == False: Customer.remove_book(book.key) #delete the book ndb.Key(urlsafe=book_id).delete() #HTTP no content self.response.set_status(204) except: #error on not found self.response.set_status(404) return #delete all books else: BookController.delete_all_books() #HTTP no content self.response.set_status(204)
def GetCustomerByName(self, pName): #logging.debug("Searching for: " + pName) tCustomerResults = [] tCustomerQuery = Customer().all() tCustomerQuery.filter('customerLastName', pName) tCustomerResults = tCustomerQuery.fetch(10) #logging.debug("Found these results: " + str(len(tCustomerResults))) return tCustomerResults
def GetCustomerByPpid(self, pPpid): #logging.debug("Searching for: " + pPpid) tCustomerResults = [] tCustomerQuery = Customer().all() tCustomerQuery.filter('customerPaypalId', pPpid) tCustomerResults = tCustomerQuery.fetch(10) #logging.debug("Found these results: " + str(len(tCustomerResults))) return tCustomerResults
def addCustomer(self, id, name, phone, location): customer = Customer() customer.setId(id) customer.setName(name) customer.setPhone(phone) customer.setLocation(location) UserService.customer_details[id] = customer return customer
def GetCustomerByEmail(self, pEmail): #logging.debug("Searching for: " + pEmail) tCustomerResults = [] tCustomerQuery = Customer().all() tCustomerQuery.filter('customerEmail', pEmail) tCustomerResults = tCustomerQuery.fetch(10) #logging.debug("Found these results: " + str(len(tCustomerResults))) return tCustomerResults
def setUp(self) -> None: self.data = { "_id": "123", "name": "Test Customer", "address": "Cairo", "phone": "0123456789", "date": "13-2-2021", } self.customer = Customer(**self.data)
def test_as_json(mockEngine, mock_customer_request_data): request_data = mock_customer_request_data.copy() customer = Customer(**request_data) request_data['created_at'] = None request_data['last_updated'] = None assert customer.as_json() == request_data
def khoi_tao(): for i in range(50): custommer = Customer(name=fake.name(), gender=randint(0, 1), email="{0}@gmail.com".format(randint(0, 9999)), phone_number=fake.phone_number(), company=fake.company(), contacted=randint(0, 1)) print(i) custommer.save()
def step_2(context): for row in context.table: try: context.customer_id = Customer.get( Customer.email == '*****@*****.**') except Customer.DoesNotExist: context.customer_id = Customer.create(email='*****@*****.**') context.order_id = Order.create(customer_id=context.customer_id, order_status=row['order_status'], district=row['district'])
def post(self): cust_email = request.json['email'] cust_name = request.json['name'] cust_address = request.json['address'] cust_phone = request.json['phone'] customer = Customer(email=cust_email, name=cust_name, address=cust_address, phone=cust_phone) customer.save_to_db() return customer.to_json(), 201
def create(): if request.method == 'GET': return render_template('new.html') elif request.method == 'POST': form = request.form name = form['name'] gender = form['gender'] phone = form['phone'] customer = Customer(name = name, gender = gender,phone = phone) customer.save() return redirect(url_for('admin'))
def updateFromPeopleSystem(self, cpf): dto = SyncronizeCustomerService().getFromPeopleSystem(cpf) if(dto == None): raise Exception('Nenhum cliente com CPF {0}'.format(cpf)) reg = Customer() reg.map(dto) self.insertOrUpdateCustomer(cpf, reg) return reg
def index(self): # Get the SQLAlchemy session associated # with this request. # It'll be released once the request # processing terminates db = cherrypy.request.db c = Customer() c.name = "First Customer" c.order_count = 1 db.add(c) cherrypy.log("bang") return "hello world"
def get(self): tCQ = Customer().all() tCQ.filter('customerPaypalId', 'NULL') tCQ = db.GqlQuery( "SELECT * FROM Customer where customerPaypalId = NULL") tList = tCQ.fetch(500) #logging.debug("Updating: " + str(len(tList))) cust = Customer() for cust in tList: cust.delete() self.response.out.write("DONE")
def get(self, customer_id=None): #if a customer id is sent, attempt to return the customer if customer_id: #if customer not found will cause an error try: customer = ndb.Key(urlsafe=customer_id).get() #make sure is customer and not book assert Customer.is_customer(customer) self.write_json(customer.to_json()) except: #error on not found self.response.set_status(404) #return list of all customers else: self.write_json(Customer.all_to_json(Customer.all()))
def mutate(root, info, campaign_id, customer_data): campaign = CampaignModel.find_by_id(campaign_id) if not campaign: raise Exception("Campaign not found!") company = campaign.company.fetch() if not company: raise Exception("Company not found!") customer = CustomerModel(**customer_data, source=campaign, company=company) customer.save() return AddCustomer(customer=customer)
def customer_register(): rds = g.rds db = g._db obj = json.loads(request.data) appid = obj.get("appid", 0) uid = obj.get("customer_id", "") name = obj.get("name", "") avatar = obj.get("avatar", "") if not appid: raise ResponseMeta(400, "invalid param") store_id = App.get_store_id(db, appid) if not store_id: raise ResponseMeta(400, "app do not support customer") if not uid: client_id = Customer.generate_client_id(rds) else: client_id = Customer.get_client_id(rds, appid, uid) if not client_id: client_id = Customer.generate_client_id(rds) Customer.set_client_id(rds, appid, uid, client_id) token = User.get_user_access_token(rds, appid, client_id) if not token: token = create_access_token() User.add_user_count(rds, appid, client_id) User.save_user(rds, appid, client_id, name, avatar, token) User.save_token(rds, appid, client_id, token) if obj.has_key("platform_id") and obj.has_key("device_id"): platform_id = obj['platform_id'] device_id = obj['device_id'] s = init_message_queue(appid, client_id, platform_id, device_id) if s: logging.error("init message queue success") else: logging.error("init message queue fail") resp = { "token": token, "store_id": store_id, "client_id": client_id, } data = {"data": resp} return make_response(200, data)
def customer_register(): rds = g.rds db = g._db obj = json.loads(request.data) appid = obj.get("appid", 0) uid = obj.get("customer_id", "") name = obj.get("name", "") avatar = obj.get("avatar", "") if not appid: raise ResponseMeta(400, "invalid param") store_id = App.get_store_id(db, appid) if not store_id: raise ResponseMeta(400, "app do not support customer") if not uid: client_id = Customer.generate_client_id(rds) else: client_id = Customer.get_client_id(rds, appid, uid) if not client_id: client_id = Customer.generate_client_id(rds) Customer.set_client_id(rds, appid, uid, client_id) token = User.get_user_access_token(rds, appid, client_id) if not token: token = create_access_token() User.add_user_count(rds, appid, client_id) User.save_user(rds, appid, client_id, name, avatar, token) User.save_token(rds, appid, client_id, token) if obj.has_key("platform_id") and obj.has_key("device_id"): platform_id = obj['platform_id'] device_id = obj['device_id'] s = init_message_queue(appid, client_id, platform_id, device_id) if s: logging.error("init message queue success") else: logging.error("init message queue fail") resp = { "token":token, "store_id":store_id, "client_id":client_id, } data = {"data":resp} return make_response(200, data)
def post(self): pEmail = self.request.get('email') pCustomerId = self.request.get('custid') pMarkVerified = self.request.get('verified') #logging.debug(str(pEmail)) #logging.debug(str(pCustomerId)) #logging.debug(str(pMarkVerified)) tCustomer = Customer.get(pCustomerId) tNumber = random.randint(200, 999) if (pMarkVerified != None and pMarkVerified == 'True'): tCustomer.customerEmailVerified = True tCustomer.put() self.response.headers[ 'Cache-Control'] = 'Cache-Control: no-cache, must-revalidate' self.response.headers['Content-Type'] = 'Content-Type: plain/text' self.response.out.write("Verified") else: tMessage = "Verification Number: " + str(tNumber) mail.send_mail(sender="Smokin Mils Goldshop <*****@*****.**>", to=pEmail, subject="Smokin Mils Goldshop Email Verification", body=tMessage) #logging.debug("Sent Verification Email to : " + pEmail + " Number: " + str(tNumber)) tCustomer.customerEmailVerificationNumber = str(tNumber) tCustomer.put() self.response.headers[ 'Cache-Control'] = 'Cache-Control: no-cache, must-revalidate' self.response.headers['Content-Type'] = 'Content-Type: plain/text' self.response.out.write("New: " + str(tNumber))
class TestCustomer(unittest.TestCase): def setUp(self) -> None: self.data = { "_id": "123", "name": "Test Customer", "address": "Cairo", "phone": "0123456789", "date": "13-2-2021", } self.customer = Customer(**self.data) def test_create_customer(self): self.assertEqual(self.customer.id, "123") self.assertEqual(self.customer.name, "Test Customer") self.assertEqual(self.customer.address, "Cairo") self.assertEqual(self.customer.phone, "0123456789") self.assertEqual(self.customer.date, "13-2-2021") def test_customer_to_json(self): expected = { "id": "123", "name": "Test Customer", "address": "Cairo", "phone": "0123456789", } result = self.customer.to_json() self.assertDictEqual(result, expected)
def get(self, customer_id): result = Customer.get_or_none(Customer.customer_id == customer_id) if result: customer = model_to_dict(result, exclude=[Customer.create_time, Customer.birth_day]) customer['create_time'] = result.create_time.strftime('%Y-%m-%d %H:%M:%S') customer['birth_day'] = result.birth_day.strftime('%Y-%m-%d %H:%M:%S') return {'result': customer}
def customer(): all_customer = Customer.objects(gender=1, contacted=False) if len(all_customer) <= 10: result_customer = all_customer else: result_customer = all_customer[0:10] return render_template('customer.html', result_customer=result_customer)
def find_one(cls, collection, field, value): if collection == 'customers': return Customer.fromjson(cls.db[collection].find_one({field: value})) if collection == 'prepaids': return Prepaid.fromjson(cls.db[collection].find_one({field: value})) if collection == 'postpaids': return Postpaid.fromjson(cls.db[collection].find_one({field: value})) if collection == 'setups': return Setup.fromjson(cls.db[collection].find_one({field: value})) if collection == 'how_to_pays': return HowToPay.fromjson(cls.db[collection].find_one({field: value})) if collection == 'how_to_topups': return HowToTopup.fromjson(cls.db[collection].find_one({field: value})) if collection == 'accounts': account = cls.db[collection].find_one({field: value}) if account is not None: return Account.fromjson(cls.find_by_id('customers', account['customer']), cls.find_by_id('prepaids', account['package']), account) else: return None if collection == 'bills': bill = cls.db[collection].find({field: value}).sort('payment_date', -1)[0] if bill is not None: return Bill.fromjson(bill, cls.find_by_id('customers', bill['customer']), cls.find_by_id('postpaids', bill['package'])) else: return None
def post(self): pEmail = self.request.get('email') pCustomerId = self.request.get('custid') pMarkVerified = self.request.get('verified') #logging.debug(str(pEmail)) #logging.debug(str(pCustomerId)) #logging.debug(str(pMarkVerified)) tCustomer = Customer.get(pCustomerId) tNumber = random.randint(200, 999) if(pMarkVerified != None and pMarkVerified == 'True'): tCustomer.customerEmailVerified = True tCustomer.put() self.response.headers['Cache-Control'] = 'Cache-Control: no-cache, must-revalidate' self.response.headers['Content-Type'] = 'Content-Type: plain/text' self.response.out.write("Verified") else: tMessage = "Verification Number: " + str(tNumber) mail.send_mail(sender = "Smokin Mils Goldshop <*****@*****.**>", to = pEmail, subject = "Smokin Mils Goldshop Email Verification", body = tMessage) #logging.debug("Sent Verification Email to : " + pEmail + " Number: " + str(tNumber)) tCustomer.customerEmailVerificationNumber = str(tNumber) tCustomer.put() self.response.headers['Cache-Control'] = 'Cache-Control: no-cache, must-revalidate' self.response.headers['Content-Type'] = 'Content-Type: plain/text' self.response.out.write("New: " + str(tNumber))
def get_offline_message(): rds = g.rds appid = request.appid customer_id = request.args.get("customer_id", "") uid = int(request.args.get("uid", 0)) if not uid and hasattr(request, 'uid'): uid = request.uid if not uid and customer_id: uid = Customer.get_client_id(rds, appid, customer_id) if not uid: raise ResponseMeta(400, "invalid uid") platform_id = int(request.args.get("platform_id", 0)) device_id = request.args.get("device_id", "") params = { "appid": appid, "uid": uid, "device_id":device_id, "platform_id":platform_id, } #获取离线消息数目 count = get_offline_count(appid, uid, platform_id, device_id) new = 1 if count > 0 else 0 data = {"data":{"count":count, "new":new}} return make_response(200, data)
def customer(): all_customer = Customer.objects(contacted=False, gender=1) if len(all_customer) < 10: first_ten_cust = all_customer else: first_ten_cust = all_customer[0:10] return render_template('customer.html', first_ten_cust=first_ten_cust)
def get(self): template_params={} mail=self.request.get('mail') name=self.request.get('name') user= User.query(User.mail == mail).get() if not user: self.error(403) self.response.write(' user Error') return customer=Customer.query(Customer.name==name, Customer.user==mail).get() if not customer: self.error(403) self.response.write('no customer') return template_params['address']=customer.address template_params['phone']=customer.phone template_params['email']=customer.email template_params['field1']=customer.field1 template_params['field2']=customer.field2 template_params['field3']=customer.field3 template_params['field4']=customer.field4 template_params['field5']=customer.field5 template_params['field6']=customer.field6 self.response.write(json.dumps(template_params))
def get_customers_by_email(email): with sqlite3.connect("./kennel.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() # Write the SQL query to get the information you want db_cursor.execute( """ select c.id, c.name, c.address, c.email, c.password FROM Customer c WHERE c.email = ? """, (email, )) customers = [] dataset = db_cursor.fetchall() for row in dataset: customer = Customer(row['id'], row['name'], row['address'], row['email'], row['password']) customers.append(customer.__dict__) return json.dumps(customers)
def get_all_customers(): with sqlite3.connect("./kennel.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() db_cursor.execute(""" SELECT c.id, c.name, c.address, c.email, c.password FROM Customer c """) customers = [] dataset = db_cursor.fetchall() for row in dataset: customer = Customer(row['id'], row['name'], row['address'], row['email'], row['password']) customers.append(customer.__dict__) return json.dumps(customers)
def get(self): mail=self.request.get('mail') name=self.request.get('name') user = User.query(User.mail == mail).get() if not user: self.error(403) self.response.write('No user - access denied') return customer=Customer.query(Customer.name==name, Customer.user==user.mail).get() if not customer: self.error(402) self.response.write('no customer') return Customer.resetCustomerHours(mail, name) self.response.write(json.dumps({"status": "OK"}))
def post(self): pEmail = self.request.get('email') pCustomerId = self.request.get('custid') pMarkVerified = self.request.get('verified') #logging.debug(str(pEmail)) #logging.debug(str(pCustomerId)) #logging.debug(str(pMarkVerified)) tCustomer = Customer() tCustomer = Customer.get(pCustomerId) if(pMarkVerified != None and pMarkVerified == 'True'): tCustomer.customerIdVerified = True tCustomer.put() self.response.headers['Cache-Control'] = 'Cache-Control: no-cache, must-revalidate' self.response.headers['Content-Type'] = 'Content-Type: plain/text' self.response.out.write("Verified")
def post(self, request): # 注册 username = request.json.get("username") password = request.json.get("password") nickname = request.json.get("nickname") account_type = request.json.get("account_type") if not all([username, password, nickname, account_type]): return JsonErrorResponse("username, password, nickname, account_type are needed", 400) new_customer = Customer( username=username, password=password, nickname=nickname, account_type=account_type ) try: new_customer.save() except Exception, e: print e return JsonErrorResponse("Fail:" + e.message)
def ProcessChargeback(self, pArgumentDic): tArgumentDic = {} tArgumentDic = pArgumentDic tCustomer = Customer() tCustomerHandler = CustomerHandler() if tArgumentDic.has_key("payer_id"): tCustomer = tCustomerHandler.GetCustomerByPpid(tArgumentDic["payer_id"])[0] tSuccess = tCustomerHandler.PaBlacklistCustomer(str(tCustomer.key())) try: tPaypalEmail = tCustomer.customerEmail # logging.debug("Adding Chargeback Email for " + tPaypalEmail) taskqueue.add(url="/emailchargeback", countdown=1, params={"email": tPaypalEmail}) except: logging.debug("Failure Queueing Chargeback Email") if tSuccess: logging.debug("Successfully PA Blacklisted " + str(tArgumentDic["payer_id"]) + " due to Chargeback") else: logging.debug("Failure PA Blacklisting " + str(tArgumentDic["payer_id"]))
def find_by_id(cls, collection, id): if collection == 'customers': return Customer.fromjson(cls.db[collection].find_one({'_id': ObjectId(id)})) if collection == 'prepaids': return Prepaid.fromjson(cls.db[collection].find_one({'_id': ObjectId(id)})) if collection == 'postpaids': return Postpaid.fromjson(cls.db[collection].find_one({'_id': ObjectId(id)})) if collection == 'accounts': return Account.fromjson(cls.db[collection].find_one({'_id': ObjectId(id)})) if collection == 'bills': return Bill.fromjson(cls.db[collection].find_one({'_id': ObjectId(id)}))
def get(self): tCQ = Customer().all() tCQ.filter('customerPaypalId', 'NULL') tCQ = db.GqlQuery("SELECT * FROM Customer where customerPaypalId = NULL") tList = tCQ.fetch(500) #logging.debug("Updating: " + str(len(tList))) cust = Customer() for cust in tList: cust.delete() self.response.out.write("DONE")
def post(self): tOffset = str(self.request.get('offset')) if(tOffset == None or tOffset == ""): tOffset = 0 else: tOffset = int(tOffset) tUnattachedCustomer = Customer() tUnattachedCustomerQuery = Customer.all() tUnattachedCustomerQuery.filter("customerMaster !=", "") tUnattachedCustomerList = tUnattachedCustomerQuery.fetch(50, offset=tOffset) #logging.debug("Started with offset: " + str(tOffset)) if(len(tUnattachedCustomerList) > 0): for tUnattachedCustomer in tUnattachedCustomerList: tUnattachedCustomer.customerMaster = "" #logging.debug("Customer: " + str(tUnattachedCustomer.customerEmail)) tUnattachedCustomer.put() tOffset = tOffset + 20 taskqueue.add(url = '/customerupdate', countdown = 0, params = { 'offset' : str(tOffset)} )
def get(self): tCQ = Customer().all() tList = tCQ.fetch(5000) #logging.debug("Updating: " + str(len(tList))) cust = Customer() for cust in tList: cust.customerEmail = str(cust.customerEmail).lower() cust.put() self.response.out.write("DONE")
def get(self): template_params={} mail=self.request.get('mail') user= User.query(User.mail == mail).get() if not user: self.error(403) self.response.write(' user Error') return hours=Customer.getAllCustomersAndHoursPerUser(user.mail) template_params['status']="OK" template_params['customersandhours']=hours self.response.write(json.dumps(template_params))
def find_list(cls, collection, field, value): list = [] results = cls.db[collection].find({field: value}) for result in results: if collection == 'customers': list.append(Customer.fromjson(result)) elif collection == 'prepaids': list.append(Prepaid.fromjson(result)) elif collection == 'postpaids': list.append(Postpaid.fromjson(result)) elif collection == 'accounts': list.append(Account.fromjson(result)) elif collection == 'bills': list.append(Bill.fromjson(result)) return list
def PostContext(self): tCustomerKey = "" tCustomer = Customer() tCustomerLookup = CustomerHandler() tAction = str(self.request.get('action')).lower() tCustomerKey = str(self.request.get('key')) tItem = str(self.request.get('item')).lower() if (tAction != None and len(tAction) > 0 and tAction == "search"): tSearchEmail = str(urllib.unquote(self.request.get('email'))).lower() tSearchPpid = str(urllib.unquote(self.request.get('ppid'))) if (tSearchEmail != None and len(tSearchEmail) > 0): tCustomerList = tCustomerLookup.GetCustomerByEmail(tSearchEmail) elif (tSearchPpid != None and len(tSearchPpid) > 0): tCustomerList = tCustomerLookup.GetCustomerByPpid(tSearchPpid) tCustomer = tCustomerList[0] elif (tCustomerKey != None and len(tCustomerKey) > 0): tCustomer = Customer().get(tCustomerKey) if (tAction == 'phone'): tCustomer.customerPhone = tItem #logging.debug("Number saving success: " + tItem) if (tAction == 'idverified'): tCustomer.customerIdVerified = True #logging.debug("Customer Id Verified") if (tAction == 'idverify'): tCustomer.customerIdLink = tItem #logging.debug("Customer Id: " + tItem) if (tAction == 'memo'): tCustomer.customerMemo = tItem #logging.debug("Customer Memo: " + tItem) tCustomer.put() if(tCustomer): tCustomerKey = str(tCustomer.key()) self.LOCATION = '/customerlookup?key=' + str(tCustomerKey) self.REDIRECT = True return {} #need to return something for processing
def post(self): pPhone = str(self.request.get('phone')) pCustomerId = self.request.get('custid') pMarkVerified = self.request.get('verified') tUserName = "******" tPass = "******" tUrl = "http://usa.bulksms.com:5567/eapi/submission/send_sms/2/2.0" tCustomer = Customer.get(pCustomerId) tNumber = random.randint(200, 999) if(pMarkVerified != None and pMarkVerified == 'True'): tCustomer.customerPhoneVerified = True tCustomer.put() self.response.headers['Cache-Control'] = 'Cache-Control: no-cache, must-revalidate' self.response.headers['Content-Type'] = 'Content-Type: plain/text' self.response.out.write("Verified") else: tMessage = "Verification Number: " + str(tNumber) tPostPackage = { 'username' : tUserName, 'password' : tPass, 'message' : tMessage, 'msisdn' : pPhone } #logging.debug("Package " + str(tPostPackage)) tPostPackage = urllib.urlencode(tPostPackage) tResponse = urlfetch.fetch(url = tUrl, payload = tPostPackage, method = "POST", headers = {}) tResponse = tResponse.content #logging.debug("Message for Phone: " + pPhone + " Response: " + tResponse) tCustomer.customerPhoneVerificationNumber = str(tNumber) tCustomer.put() self.response.headers['Cache-Control'] = 'Cache-Control: no-cache, must-revalidate' self.response.headers['Content-Type'] = 'Content-Type: plain/text' self.response.out.write("New: " + str(tNumber))
def ProcessOrder(self, pArgumentDic): tOrderHandler = OrderHandler() tCustomerHandler = CustomerHandler() tCustomer = Customer() tPaypalOrder = PaypalOrder() tArgumentDic = pArgumentDic # Assign Values from POST from Paypal IPN tTransactionId = tArgumentDic["txn_id"] tAlphaMatch = re.compile("[^A-Za-z0-9]+") tAlphaSpaceMatch = re.compile("[^A-Za-z0-9 ]+") # Short circuits the order process for special PA page if "payer_email" in tArgumentDic.keys(): if tArgumentDic["payer_email"] == "*****@*****.**": tPaypalOrder.ProcessPlayerAuctions(tArgumentDic) return try: tGoldAmount = tArgumentDic["option_name7"] except: tGoldAmount = "" try: tCustomerFirstName = tAlphaSpaceMatch.sub("", tArgumentDic["first_name"]) except: tCustomerFirstName = "" try: tCustomerLastName = tAlphaSpaceMatch.sub("", tArgumentDic["last_name"]) except: tCustomerLastName = "" try: tCustomerName = tAlphaSpaceMatch.sub("", tArgumentDic["option_name1"]) except: tCustomerName = "" try: tEmail = tArgumentDic["option_name2"] except: tEmail = "" tPaypalEmail = str(tArgumentDic["payer_email"]).lower() try: tMobilePhone = tArgumentDic["option_name3"] tMobilePhone = re.sub(r"\D", "", tMobilePhone) except: tMobilePhone = "" try: tRsName = tArgumentDic["option_name4"].strip().lower() tRsName = tRsName.replace(" ", "_") tRsName = tRsName.replace("-", "_") except: tRsName = "" try: tCombatLevel = "" except: tCombatLevel = "" # try: # tReferCode = str(tArgumentDic['option_name5']).strip() # except: tReferCode = "" try: tPromotionCode = str(tArgumentDic["option_name5"]).strip() except: tPromotionCode = "" tOrderIp = tArgumentDic["custom"] tMembers = "" try: tOrderQuery = Order.all().filter("orderTransactionId", tTransactionId) tOrder = tOrderQuery.fetch(1)[0] except: tOrder = Order() if "fake" in tArgumentDic.keys(): # logging.debug('Fake key hit') # logging.debug(str(tArgumentDic['fake'])) if tArgumentDic["fake"] == "True": tOrder.orderIsGenerated = True tOrder.orderFormName = tCustomerName tOrder.orderCombatLevel = tCombatLevel if len(tGoldAmount) == 0: tUrl = "https://api-3t.paypal.com/nvp" # tOperation = "AddressVerify" tOperation = "GetTransactionDetails" # Get Paypal Information # tPaypal = PaypalTrigger() tResultDictionary = {} tPaypalPayload = {} tPayload = {} tPaypalPayload["METHOD"] = tOperation tPaypalPayload["TRANSACTIONID"] = tTransactionId tPayloadEncoded = tOrderHandler.GeneratePayload(tPaypalPayload) request_cookies = mechanize.CookieJar() request_opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(request_cookies)) request_opener.addheaders = [("Content-Type", "application/x-www-form-urlencoded")] mechanize.install_opener(request_opener) tResponse = mechanize.urlopen(url=tUrl, timeout=25.0, data=tPayloadEncoded) tResult = str(urllib.unquote(tResponse.read())) tResultSplit = tResult.split("&") for tPair in tResultSplit: tSplitPair = tPair.split("=") if len(tSplitPair) == 1: tSplitPair.append("") tResultDictionary[tSplitPair[0]] = tSplitPair[1] logging.debug(tSplitPair[0] + " " + tSplitPair[1]) tGoldAmountString = tResultDictionary["L_NAME0"] logging.debug("Gold amount string %s".format(tGoldAmountString)) try: tGoldRegex = re.compile("([0-9]*?[m|M]).T") tGoldMatch = tGoldRegex.findall(tGoldAmountString) # logging.debug("Backup gold amount parser hit, string " + tGoldAmountString + " Match: " + tGoldMatch[0]) tGoldAmount = tGoldMatch[0] except: tGoldRegex = re.compile("([0-9]*?[m|M]).T") tGoldMatch = tGoldRegex.findall(tGoldAmountString) try: # logging.debug("Backup gold amount parser hit, string " + tGoldAmountString + " Match: " + tGoldMatch[0]) tGoldAmount = tGoldMatch[0] except: # logging.debug("No gold match") tGoldAmount = "" tOrder.orderQuantity = NumberToGp.ConvertBetToInt(tGoldAmount) tOrder.orderSimpleGoldAmount = tGoldAmount tOrder.orderFormEmail = tEmail tOrder.orderAccountName = tRsName tOrder.orderMobileNumber = tMobilePhone tOrder.orderPromotionalCode = tPromotionCode.lower() tOrder.orderIp = tOrderIp if tMembers == "yes": tOrder.orderCustomerIsMember = True else: tOrder.orderCustomerIsMember = False # Paypal Info tOrder.orderTransactionId = tTransactionId tOrder.orderPaypalFirstName = tCustomerFirstName tOrder.orderPaypalLastName = tCustomerLastName tOrder.orderCost = float(tArgumentDic["payment_gross"]) tOrder.orderCustomerPaypalId = tArgumentDic["payer_id"] tOrder.orderPaypalEmail = str(tPaypalEmail).lower() tAssignedAgentNick = tPaypalOrder.GetAssignedAgent(tOrder) tOrder.orderAssignedAgent = tAssignedAgentNick # logging.debug("Order assigned to agent: " + str(tAssignedAgentNick)) tOrder.orderReferralCode = tReferCode tOrder.orderDeliver = "False" if tOrder.orderVerificationCode == None or tOrder.orderVerificationCode == "": tOrder.orderVerificationCode = re.sub(r"\W", "", str(uuid.uuid4())).lower() tCurrentEocPrices = PriceContainer.GetCurrentPriceDic() tCurrent07Prices = PriceContainer.GetCurrentPriceDic07() tSkip07 = False if tOrder.orderSimpleGoldAmount in tCurrentEocPrices.keys(): if str(tOrder.orderCost) == str(tCurrentEocPrices[tOrder.orderSimpleGoldAmount]): tOrder.orderGoldType = "eoc" tSkip07 = True if not tSkip07: if tOrder.orderSimpleGoldAmount in tCurrent07Prices.keys(): if str(tOrder.orderCost) == str(tCurrent07Prices[tOrder.orderSimpleGoldAmount]): tOrder.orderGoldType = "07" tOrderKey = str(tOrder.put()) # logging.debug("Order Saved: " + str(tOrderKey)) taskqueue.add(url="/iplookup", countdown=1, params={"ip": tOrderIp, "transid": tTransactionId}) tUsedBonus = [] tCustomerList = tCustomerHandler.GetCustomerByPpid(tOrder.orderCustomerPaypalId) if len(tCustomerList) == 1: tCustomer = tCustomerList[0] tIpList = tCustomer.customerIpAddresses tIpList.append(tOrderIp) tCustomer.customerIpAddresses = tIpList tOrderList = tCustomer.customerOrders tOrderList.append(tOrderKey) tCustomer.customerOrders = tOrderList tCustomer.customerOrderCount = int(tCustomer.customerOrderCount) + 1 # tUsedBonus = tCustomer.customerUsedBonus tUsedBonus = Order.GetCustomerPromoCodes(tCustomer.customerPaypalId) # tOrder.orderCustomer = str(tCustomer.key()) elif len(tCustomerList) == 0: tCustomer.customerEmail = str(tOrder.orderPaypalEmail).lower() tCustomer.customerName = tCustomerName tCustomer.customerFirstName = tOrder.orderPaypalFirstName tCustomer.customerLastName = tOrder.orderPaypalLastName tCustomer.customerIpAddresses = [tOrderIp] tCustomer.customerOrders = [tOrderKey] tCustomer.customerOrderCount = 1 tCustomer.customerPhone = tMobilePhone tCustomer.customerEmailVerified = False tCustomer.customerPhoneVerified = False tCustomer.customerIdVerified = False tCustomer.customerPaypalId = tOrder.orderCustomerPaypalId tCustomer.customerIsGlobalBlacklisted = False tCustomer.customerIsPaBlacklisted = False tPromoCode = "" tPromoCode = tOrder.orderPromotionalCode # logging.debug("Order Promo Code: " + str(tOrder.orderPromotionalCode)) tPromo = Promo() tPromoCode = tPromoCode.lower() try: logging.debug("Promo Code: " + str(tPromoCode)) tPromo = Promo.GetPromoByCode(tPromoCode) logging.debug("Promo: " + str(tPromo)) tGoldAmount = tOrder.orderQuantity logging.debug("Gold Amount: " + str(tGoldAmount)) logging.debug("Promo is active: " + str(tPromo.promoIsActive)) if (tPromo.promoIsActive) and (tPromo.promoUses <= tPromo.promoLimit): if tPromo.promoLimit != 0: tPromo.promoUses = tPromo.promoUses + 1 if (tPromoCode in tUsedBonus) == True: tPercentBonus = 0.0 else: tPercentBonus = tGoldAmount * tPromo.promoPercentage # tUsedBonus.append(tPromoCode) tGoldAmount = tGoldAmount + tPercentBonus tGoldAmount = tGoldAmount + tPromo.promoGoldAmount tTotalBonusFloat = tPercentBonus + tPromo.promoGoldAmount logging.debug("Bonus float: " + str(tTotalBonusFloat)) tOrder.orderBonusQuantity = int(tTotalBonusFloat) logging.debug("Total Bonus Float " + str(tTotalBonusFloat)) logging.debug("Promo Gold Amount " + str(tPromo.promoGoldAmount)) logging.debug("Promo Percentage " + str(tPercentBonus)) except: tOrder.orderBonusQuantity = 0 # tCustomer.customerUsedBonus = tUsedBonus tCustomerKey = str(tCustomer.put()) tOrder.orderCustomer = tCustomerKey tOrderKey = str(tOrder.put()) if tCustomerName == "": tCustomerName = tCustomerFirstName + " " + tCustomerLastName if tGoldAmount == None or len(str(tGoldAmount)) == 0: tGoldAmount = tGoldAmountString response = taskqueue.add( url="/emailnotify", countdown=1, params={"email": tPaypalEmail, "gold": tGoldAmount, "name": tCustomerName, "key": tOrderKey}, ) logging.debug(str(response))
def _get_current_user(): customer_key = Customer.create_key(users.get_current_user()) return customer_key.get()
def get(self): tOrder = Order() tUnattachedCustomer = Customer() tMasterCustomer = CustomerMaster() tMasterCustomer.masterIsPaBlacklisted = False tMasterCustomer.masterIsGlobalBlacklisted = False #Lists of customer masters tMasterCustomerEmailList = [] tMasterCustomerIpList = [] tMasterCustomerPhoneList = [] tMasterCustomerRsnList = [] tMasterCustomerPaypalList = [] tMasterCustomerEmailQuery = CustomerMaster.all() tMasterCustomerIpQuery = CustomerMaster.all() tMasterCustomerPhoneQuery = CustomerMaster.all() tMasterCustomerRsnQuery = CustomerMaster.all() tMasterCustomerPaypalQuery = CustomerMaster.all() #Final lists for deletion tDeletionList = [] #First get an unmastered customer tUnattachedCustomerQuery = Customer.all() tUnattachedCustomerQuery.filter("customerMaster", "") #tUnattachedCustomerQuery.filter("customerEmail", "*****@*****.**") tUnattachedCustomerList = tUnattachedCustomerQuery.fetch(1) if(len(tUnattachedCustomerList) > 0): tUnattachedCustomer = tUnattachedCustomerList[0] else: return #logging.debug("Testing with customer: " + str(tUnattachedCustomer.customerEmail)) #Defaults tEmail = "" tPhone = "" tIpList = [] #Assign from unmastered customer tEmail = str(tUnattachedCustomer.customerEmail).strip().lower() tPhone = str(tUnattachedCustomer.customerPhone).strip().lower() tPhone = re.sub(r'\D', '', tPhone) for tIp in tUnattachedCustomer.customerIpAddresses: tIp = str(tIp).strip() if (tIp != '' and tIp != None): tIpList.append(tIp) #Get Customer's Orders tOrderQuery = Order.all() tOrderQuery.filter("orderPaypalEmail", tEmail) tOrderList = tOrderQuery.fetch(200) #Merge together a list of the RSNs and Order Paypal IDs tRsnList = [] tPaypalList = [] for tOrder in tOrderList: if(tOrder.orderAccountName != None and tOrder.orderAccountName != ""): tTempRsn = str(tOrder.orderAccountName).lower().strip() tTempRsn = tTempRsn.replace(' ', '_') tTempRsn = tTempRsn.replace('-', '_') tRsnList.append(tTempRsn) if(tOrder.orderCustomerPaypalId != None and tOrder.orderCustomerPaypalId != ""): tPaypalList.append(str(tOrder.orderCustomerPaypalId)) #Dedupification tIpList = list(set(tIpList)) tRsnList = list(set(tRsnList)) tPaypalList = list(set(tPaypalList)) #Now that the data to search is filled we can start searching for masters if(tEmail != None and tEmail != ""): #logging.debug("Searching for masters with customer email: " + str(tEmail)) tMasterCustomerEmailQuery.filter("masterEmailList", tEmail) tMasterCustomerEmailList = tMasterCustomerEmailQuery.fetch(200) if(tPhone != None and tPhone != ""): #logging.debug("Searching for masters with customer phone: " + str(tPhone)) tMasterCustomerPhoneQuery.filter("masterPhoneList", tPhone) tMasterCustomerPhoneList = tMasterCustomerPhoneQuery.fetch(200) if(len(tIpList) > 0): for tIp in tIpList: if(tIp != None and tIp != ""): #logging.debug("Searching for masters with customer ip: " + str(tIp)) tMasterCustomerIpQuery = CustomerMaster.all() tMasterCustomerIpQuery.filter("masterIpList", tIp) tMasterCustomerIpList += tMasterCustomerIpQuery.fetch(200) if(len(tRsnList) > 0): for tRsn in tRsnList: if(tRsn != None and tRsn != ""): #logging.debug("Searching for masters with customer rsn: " + str(tRsn)) tMasterCustomerRsnQuery = CustomerMaster.all() tMasterCustomerRsnQuery.filter("masterRsnList", tRsn) tMasterCustomerRsnList += tMasterCustomerRsnQuery.fetch(200) if(len(tPaypalList) > 0): for tPaypal in tPaypalList: if(tPaypal != None and tPaypal != ""): #logging.debug("Searching for masters with customer paypal id: " + str(tPaypal)) tMasterCustomerPaypalQuery = CustomerMaster.all() tMasterCustomerPaypalQuery.filter("masterPaypalIdList", tPaypal) tMasterCustomerPaypalList += tMasterCustomerPaypalQuery.fetch(200) #logging.debug("Paypal Ids "+ str(tPaypalList)) #logging.debug("") #Merge the lists together tMasterCustomerList = [] tMasterCustomerList = tMasterCustomerEmailList + tMasterCustomerIpList + tMasterCustomerPaypalList + tMasterCustomerPhoneList + tMasterCustomerRsnList #if(len(tMasterCustomerEmailList) > 0): ##logging.debug("Master customer email list: " + str(tMasterCustomerEmailList)) #tMasterCustomerList += tMasterCustomerEmailList #if(len(tMasterCustomerPhoneList) > 0): ##logging.debug("Master customer phone list: " + str(tMasterCustomerPhoneList)) #tMasterCustomerList += tMasterCustomerPhoneList #if(len(tMasterCustomerIpList) > 0): ##logging.debug("Master customer ip list: " + str(tMasterCustomerIpList)) #tMasterCustomerList += tMasterCustomerIpList #if(len(tMasterCustomerRsnList) > 0): ##logging.debug("Master customer rsn list: " + str(tMasterCustomerRsnList)) #tMasterCustomerList += tMasterCustomerRsnList #if(len(tMasterCustomerPaypalList) > 0): ##logging.debug("Master customer paypalid list: " + str(tMasterCustomerPaypalList)) #tMasterCustomerList += tMasterCustomerPaypalList #logging.debug("Number of Master Customers: " + str(len(tMasterCustomerList))) #ttMC = CustomerMaster() #for ttMC in tMasterCustomerList: #logging.debug("Master customer list item key: " + str(ttMC.key())) #logging.debug(str(tMasterCustomerList)) #Assign or append lists of master customers if(len(tMasterCustomerList) > 1): tMC = CustomerMaster() tMcEmailList = [] tMcPhoneList = [] tMcIpList = [] tMcRsnList = [] tMcPaypalList = [] tMcCustomerList = [] for tMC in tMasterCustomerList: tMcEmailList += tMC.masterEmailList tMcPhoneList += tMC.masterPhoneList tMcIpList += tMC.masterIpList tMcRsnList += tMC.masterRsnList tMcPaypalList += tMC.masterPaypalIdList tMcCustomerList += tMC.masterCustomerList tDeletionList += [tMC] #for tMC in tMasterCustomerList: #if(len(tMC.masterEmailList) > 0): #tMcEmailList += tMC.masterEmailList ##tMcEmailList += tMasterCustomer.masterEmailList #if(len(tMC.masterPhoneList) > 0): #tMcPhoneList += tMC.masterPhoneList ##tMcPhoneList += tMasterCustomer.masterPhoneList #if(len(tMC.masterIpList) > 0): #tMcIpList += tMC.masterIpList ##tMcIpList += tMasterCustomer.masterIpList #if(len(tMC.masterRsnList) > 0): #tMcRsnList += tMC.masterRsnList ##tMcRsnList += tMasterCustomer.masterRsnList #if(len(tMC.masterPaypalIdList) > 0): #tMcPaypalList += tMC.masterPaypalIdList ##tMcPaypalList += tMasterCustomer.masterPaypalIdList #if(len(tMC.masterCustomerList) > 0): #tMcCustomerList += tMC.masterCustomerList ##tMcCustomerList += tMasterCustomer.masterCustomerList #tDeletionList += [tMC] tMcEmailList += [tEmail] tMcPhoneList += [tPhone] tMcIpList += tIpList tMcPaypalList += tPaypalList tMcRsnList += tRsnList tMcCustomerList += [str(tUnattachedCustomer.key())] tMasterCustomer.masterEmailList += list(set([str(x) for x in tMcEmailList if x != '' and x != None])) tMasterCustomer.masterPhoneList += list(set([str(x) for x in tMcPhoneList if x != '' and x != None])) tMasterCustomer.masterIpList += list(set([str(x).strip() for x in tMcIpList if x != '' and x != None])) tMasterCustomer.masterRsnList += list(set([str(x).strip().lower().replace('-','_').replace(' ','_') for x in tMcRsnList if x != '' and x != None])) tMasterCustomer.masterPaypalIdList += list(set([str(x) for x in tMcPaypalList if x != '' and x != None])) tMasterCustomer.masterCustomerList += list(set([str(x) for x in tMcCustomerList if x != '' and x != None])) ############################################################################################################################################## elif(len(tMasterCustomerList) == 1): tMC = tMasterCustomerList[0] #if(len(tMC.masterEmailList) > 0): #tMasterCustomer.masterEmailList += list(set([x for x in tMC.masterEmailList if x != '' and x != None])) #if(len(tMC.masterPhoneList) > 0): #tMasterCustomer.masterPhoneList += list(set([x for x in tMC.masterPhoneList if x != '' and x != None])) #if(len(tMC.masterIpList) > 0): #tMasterCustomer.masterIpList += list(set([x for x in tMC.masterIpList if x != '' and x != None])) #if(len(tMC.masterRsnList) > 0): #tMasterCustomer.masterRsnList += list(set([str(x).strip().lower().replace('-','_').replace(' ','_') for x in tMC.masterRsnList if x != '' and x != None])) #if(len(tMC.masterPaypalIdList) > 0): #tMasterCustomer.masterPaypalIdList += list(set([x for x in tMC.masterPaypalIdList if x != '' and x != None])) tMC.masterEmailList += [tEmail] tMC.masterIpList += tIpList tMC.masterPaypalIdList += tPaypalList tMC.masterPhoneList += [tPhone] tMC.masterRsnList += tRsnList tMasterCustomer.masterEmailList += list(set([x for x in tMC.masterEmailList if x != '' and x != None])) tMasterCustomer.masterPhoneList += list(set([x for x in tMC.masterPhoneList if x != '' and x != None])) tMasterCustomer.masterIpList += list(set([x for x in tMC.masterIpList if x != '' and x != None])) tMasterCustomer.masterRsnList += list(set([str(x).strip().lower().replace('-','_').replace(' ','_') for x in tMC.masterRsnList if x != '' and x != None])) tMasterCustomer.masterPaypalIdList += list(set([x for x in tMC.masterPaypalIdList if x != '' and x != None])) tMasterCustomer.masterCustomerList += [str(tUnattachedCustomer.key())] tDeletionList = [tMC] ############################################################################################################################################## elif(len(tMasterCustomerList) == 0): if(tMasterCustomer.masterCustomerList == None or len(tMasterCustomer.masterCustomerList) == 0): tTempList = [] try: tTempList.append(str(tUnattachedCustomer.key())) except: tUnattachedCustomer.put() tTempList.append(str(tUnattachedCustomer.key())) tMasterCustomer.masterCustomerList += tTempList if(tMasterCustomer.masterEmailList == None or len(tMasterCustomer.masterEmailList) == 0): tTempList = [] tTempList.append(str(tUnattachedCustomer.customerEmail)) tMasterCustomer.masterEmailList += tTempList if(tMasterCustomer.masterIpList == None or len(tMasterCustomer.masterIpList) == 0): tTempList = [] tTempList += list(set(tUnattachedCustomer.customerIpAddresses)) tMasterCustomer.masterIpList += tTempList if(tMasterCustomer.masterPaypalIdList == None or len(tMasterCustomer.masterPaypalIdList) == 0): tTempList = [] tTempList.append(str(tUnattachedCustomer.customerPaypalId)) tMasterCustomer.masterPaypalIdList += tTempList if(tMasterCustomer.masterPhoneList == None or len(tMasterCustomer.masterPhoneList) == 0): tTempList = [] tTempList.append(str(tUnattachedCustomer.customerPhone)) tMasterCustomer.masterPhoneList += tTempList if(tMasterCustomer.masterRsnList == None or len(tMasterCustomer.masterRsnList) == 0): tTempList = [] tTempList += list(set(tRsnList)) tMasterCustomer.masterRsnList += tTempList if(tUnattachedCustomer.customerIsPaBlacklisted == True): tMasterCustomer.masterIsPaBlacklisted = True if(tUnattachedCustomer.customerIsGlobalBlacklisted == True): tMasterCustomer.masterIsGlobalBlacklisted = True #for tProperty, tValue in tUnattachedCustomer.__dict__.iteritems(): #logging.debug("Customer property " + str(tProperty) + " with value " + str(tValue)) #for tProperty, tValue in tMasterCustomer.__dict__.iteritems(): #logging.debug("Master property " + str(tProperty) + " with value " + str(tValue)) tMaster = CustomerMaster() if(len(tDeletionList) > 0): for tMaster in tDeletionList: tMaster.delete() tMasterKey = tMasterCustomer.put() #update other customers if there's >1 tUnattachedCustomer.customerMaster = str(tMasterKey) tUnattachedCustomer.put() tCustomer = Customer() for tCustomerKey in tMasterCustomer.masterCustomerList: tCustomer = Customer.get(tCustomerKey) tCustomer.customerMaster = str(tMasterKey) tCustomer.put() #logging.debug("Master Key: " + str(tMasterKey))
def post(self): tCustomerHandler = CustomerHandler() tCustomer = Customer() tPhoneLookup = PhoneLookup() tPhone = Phone() #tPhoneNumber = str(self.request.get('phone')) tPhoneOrder = str(self.request.get('order')) tPhoneCustomer = str(self.request.get('customer')) tIpCountry = str(self.request.get('ipcountry')) tPhoneInfo = {} tCustomer = tCustomerHandler.GetCustomerByKey(tPhoneCustomer) tPhoneNumber = tCustomer.customerPhone #strips non numberic characters from number tPhoneNumber = re.sub('\D', '', tPhoneNumber) #removes leading 0s try: while(tPhoneNumber[0] == '0'): tPhoneNumber = tPhoneNumber[1:] tTupleList = [('Afghanistan', '93'), ('Albania', '355'), ('Algeria', '213'), ('American Samoa', '1684'), ('Andorra', '376'), ('Angola', '244'), ('Anguilla', '1264'), ('Antarctica', '672'), ('Antigua and Barbuda', '1268'), ('Argentina', '54'), ('Armenia', '374'), ('Aruba', '297'), ('Australia', '61'), ('Austria', '43'), ('Azerbaijan', '994'), ('Bahamas', '1 242'), ('Bahrain', '973'), ('Bangladesh', '880'), ('Barbados', '1246'), ('Belarus', '375'), ('Belgium', '32'), ('Belize', '501'), ('Benin', '229'), ('Bermuda', '1441'), ('Bhutan', '975'), ('Bolivia', '591'), ('Bosnia and Herzegovina', '387'), ('Botswana', '267'), ('Brazil', '55'), ('British Indian Ocean Territory', ''), ('British Virgin Islands', '1 284'), ('Brunei', '673'), ('Bulgaria', '359'), ('Burkina Faso', '226'), ('Burma (Myanmar)', '95'), ('Burundi', '257'), ('Cambodia', '855'), ('Cameroon', '237'), ('Canada', '1'), ('Cape Verde', '238'), ('Cayman Islands', '1345'), ('Central African Republic', '236'), ('Chad', '235'), ('Chile', '56'), ('China', '86'), ('Christmas Island', '61'), ('Cocos (Keeling) Islands', '61'), ('Colombia', '57'), ('Comoros', '269'), ('Republic of the Congo', '242'), ('Democratic Republic of the Congo', '243'), ('Cook Islands', '682'), ('Costa Rica', '506'), ('Croatia', '385'), ('Cuba', '53'), ('Cyprus', '357'), ('Czech Republic', '420'), ('Denmark', '45'), ('Djibouti', '253'), ('Dominica', '1767'), ('Dominican Republic', '1809'), ('Timor-Leste', '670'), ('Ecuador', '593'), ('Egypt', '20'), ('El Salvador', '503'), ('Equatorial Guinea', '240'), ('Eritrea', '291'), ('Estonia', '372'), ('Ethiopia', '251'), ('Falkland Islands', '500'), ('Faroe Islands', '298'), ('Fiji', '679'), ('Finland', '358'), ('France', '33'), ('French Polynesia', '689'), ('Gabon', '241'), ('Gambia', '220'), ('Gaza Strip', '970'), ('Georgia', '995'), ('Germany', '49'), ('Ghana', '233'), ('Gibraltar', '350'), ('Greece', '30'), ('Greenland', '299'), ('Grenada', '1473'), ('Guam', '1671'), ('Guatemala', '502'), ('Guinea', '224'), ('Guinea-Bissau', '245'), ('Guyana', '592'), ('Haiti', '509'), ('Honduras', '504'), ('Hong Kong', '852'), ('Hungary', '36'), ('Iceland', '354'), ('India', '91'), ('Indonesia', '62'), ('Iran', '98'), ('Iraq', '964'), ('Ireland', '353'), ('Isle of Man', '44'), ('Israel', '972'), ('Italy', '39'), ('Ivory Coast', '225'), ('Jamaica', '1876'), ('Japan', '81'), ('Jersey', ''), ('Jordan', '962'), ('Kazakhstan', '7'), ('Kenya', '254'), ('Kiribati', '686'), ('Kosovo', '381'), ('Kuwait', '965'), ('Kyrgyzstan', '996'), ('Laos', '856'), ('Latvia', '371'), ('Lebanon', '961'), ('Lesotho', '266'), ('Liberia', '231'), ('Libya', '218'), ('Liechtenstein', '423'), ('Lithuania', '370'), ('Luxembourg', '352'), ('Macau', '853'), ('Macedonia', '389'), ('Madagascar', '261'), ('Malawi', '265'), ('Malaysia', '60'), ('Maldives', '960'), ('Mali', '223'), ('Malta', '356'), ('Marshall Islands', '692'), ('Mauritania', '222'), ('Mauritius', '230'), ('Mayotte', '262'), ('Mexico', '52'), ('Micronesia', '691'), ('Moldova', '373'), ('Monaco', '377'), ('Mongolia', '976'), ('Montenegro', '382'), ('Montserrat', '1 664'), ('Morocco', '212'), ('Mozambique', '258'), ('Namibia', '264'), ('Nauru', '674'), ('Nepal', '977'), ('Netherlands', '31'), ('Netherlands Antilles', '599'), ('New Caledonia', '687'), ('New Zealand', '64'), ('Nicaragua', '505'), ('Niger', '227'), ('Nigeria', '234'), ('Niue', '683'), ('Norfolk Island', '672'), ('Northern Mariana Islands', '1670'), ('North Korea', '850'), ('Norway', '47'), ('Oman', '968'), ('Pakistan', '92'), ('Palau', '680'), ('Panama', '507'), ('Papua New Guinea', '675'), ('Paraguay', '595'), ('Peru', '51'), ('Philippines', '63'), ('Pitcairn Islands', '870'), ('Poland', '48'), ('Portugal', '351'), ('Puerto Rico', '1'), ('Qatar', '974'), ('Romania', '40'), ('Russia', '7'), ('Rwanda', '250'), ('Saint Barthelemy', '590'), ('Samoa', '685'), ('San Marino', '378'), ('Sao Tome and Principe', '239'), ('Saudi Arabia', '966'), ('Senegal', '221'), ('Serbia', '381'), ('Seychelles', '248'), ('Sierra Leone', '232'), ('Singapore', '65'), ('Slovakia', '421'), ('Slovenia', '386'), ('Solomon Islands', '677'), ('Somalia', '252'), ('South Africa', '27'), ('South Korea', '82'), ('Spain', '34'), ('Sri Lanka', '94'), ('Saint Helena', '290'), ('Saint Kitts and Nevis', '1869'), ('Saint Lucia', '1758'), ('Saint Martin', '1599'), ('Saint Pierre and Miquelon', '508'), ('Saint Vincent and the Grenadines', '1784'), ('Sudan', '249'), ('Suriname', '597'), ('Svalbard', ''), ('Swaziland', '268'), ('Sweden', '46'), ('Switzerland', '41'), ('Syria', '963'), ('Taiwan', '886'), ('Tajikistan', '992'), ('Tanzania', '255'), ('Thailand', '66'), ('Togo', '228'), ('Tokelau', '690'), ('Tonga', '676'), ('Trinidad and Tobago', '1 868'), ('Tunisia', '216'), ('Turkey', '90'), ('Turkmenistan', '993'), ('Turks and Caicos Islands', '1649'), ('Tuvalu', '688'), ('United Arab Emirates', '971'), ('Uganda', '256'), ('United Kingdom', '44'), ('Ukraine', '380'), ('Uruguay', '598'), ('United States', '1'), ('Uzbekistan', '998'), ('Vanuatu', '678'), ('Holy See (Vatican City)', '39'), ('Venezuela', '58'), ('Vietnam', '84'), ('US Virgin Islands', '1340'), ('Wallis and Futuna', '681'), ('West Bank', '970'), ('Western Sahara', ''), ('Yemen', '967'), ('Zambia', '260'), ('Zimbabwe', '263')] tCountryDictionary = {} for tTuple in tTupleList: tCountryDictionary[tTuple[0]] = tTuple[1] tCountryCode = tCountryDictionary[tIpCountry] tCodeLength = len(str(tCountryCode)) if (tCodeLength == 1): tTestCode = tPhoneNumber[:1] elif (tCodeLength == 2): tTestCode = tPhoneNumber[:2] elif (tCodeLength == 3): tTestCode = tPhoneNumber[:3] elif (tCodeLength == 4): tTestCode = tPhoneNumber[:4] if (tTestCode != tCountryCode): tPhoneNumber = tCountryCode + tPhoneNumber tCustomer.customerPhone = tPhoneNumber tCustomer.put() tPhoneInfo = tPhoneLookup.PhoneScraper(tPhoneNumber) tPhone.phoneNumber = tPhoneNumber tPhone.phoneCustomer = tPhoneCustomer tPhone.phoneOrder = tPhoneOrder try: tPhone.phoneCountry = tPhoneInfo['country'] except: tPhone.phoneCountry = "Unknown" try: tPhone.phoneState = tPhoneInfo['state'] except: tPhone.phoneState = "Unknown" tPhoneKey = tPhone.put() #logging.debug("Stored Phone Number: " + str(tPhoneNumber) + " at Key " + str(tPhoneKey)) except: logging.debug("Error Storing " + str(tPhoneNumber))
def GetCustomerByKey(self, pKey): tCustomer = Customer.get(pKey) return tCustomer
def GetContext(self): tUser = self.GetUser() tCustomerOrders = [] tOrderData = {} tContext = {} tOrder = Order() tCustomer = Customer() tIpHandler = IpLookup() tIpInfo = IpInfo() tDeliveryAgent = Agent() tRefundAgent = Agent() tAssignedAgent = Agent() tPriceDic = PriceContainer.GetCurrentPriceDic() tCountryDic = CountryContainer.GetCurrentCountryCodes() tOrderKey = str(urllib.unquote(self.request.get('key'))) if(tOrderKey != None and len(tOrderKey) > 0): tOrder = Order.get(tOrderKey) if(tOrder): tOrderHandler = OrderHandler() tResultDictionary = {} tPaypalPayload = {} tPayload = {} tUrl = "https://api-3t.paypal.com/nvp" tOperation = "GetTransactionDetails" tCustomer = Customer.get(tOrder.orderCustomer) # disabled to try to trace the "empty order" bug #if tOrder.orderVerificationCode is None: #tOrder.orderVerificationCode = str(uuid.uuid4()) #tOrder.put() try: tIpInfo = tIpHandler.GetIp(tOrder.orderIp)[0] except: tIpInfo.ipCountry = "Loading" tIpInfo.ipState = "Loading" tIpInfo.ipHost = "Loading" tIpInfo.ipProxy = "Loading" tIpInfo.ipIsp = "Loading" tIpInfo.ipType = "Loading" if (tIpInfo.ipProxy == ""): tIpInfo.ipProxy = 'No Proxy' tContext['tDisplayDeliver'] = 'True' #Get Paypal Information tPaypalPayload['METHOD'] = tOperation tPaypalPayload['TRANSACTIONID'] = tOrder.orderTransactionId #logging.debug("Order Paypal Email: " + tOrder.orderPaypalEmail) try: tPayloadEncoded = tOrderHandler.GeneratePayload(tPaypalPayload) request_cookies = mechanize.CookieJar() request_opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(request_cookies)) request_opener.addheaders = [('Content-Type', 'application/x-www-form-urlencoded')] mechanize.install_opener(request_opener) tResponse = mechanize.urlopen(url = tUrl, timeout = 25.0, data = tPayloadEncoded) except: tContext['error'] = 'Unable to Connect to Paypal, Try Refreshing' tContext['showerror'] = 'True' #tmpl = os.path.join(os.path.dirname(__file__), '../views/order.html') #self.response.out.write(render(tmpl, tContext)) return tContext tResult = str(urllib.unquote(tResponse.read())) tResultSplit = tResult.split('&') for tPair in tResultSplit: tSplitPair = tPair.split("=") try: tResultDictionary[tSplitPair[0]] = tSplitPair[1] #logging.debug(tSplitPair[0] + " " + tSplitPair[1]) except: logging.error("Error splitting item: " + str(tPair)) if('COUNTRYCODE' in tResultDictionary.keys()): tCountryCode = tResultDictionary['COUNTRYCODE'] tPaypalCountry = tCountryDic[tCountryCode] else: tPaypalCountry = 'UNKNOWN' tOrderData['paypalcountry'] = tPaypalCountry if 'PROTECTIONELIGIBILITYTYPE' in tResultDictionary.keys(): tProtectionEligibility = tResultDictionary['PROTECTIONELIGIBILITYTYPE'] if tProtectionEligibility == 'ItemNotReceivedEligible,UnauthorizedPaymentEligible': tProtectionEligibility = 'Eligible' if tProtectionEligibility != 'Eligible': tProtectionEligibility = 'Not Eligible' tContext['PROTECTIONELIGIBILITYTYPE'] = tProtectionEligibility else: tProtectionEligibility = 'UNKNOWN' #Display address fields if 'ADDRESSSTATUS' in tResultDictionary.keys(): tContext['ADDRESSSTATUS'] = tResultDictionary['ADDRESSSTATUS'] else: tContext['ADDRESSSTATUS'] = 'UNKNOWN' if 'SHIPTONAME' in tResultDictionary.keys(): tContext['SHIPTONAME'] = tResultDictionary['SHIPTONAME'] else: tContext['SHIPTONAME'] = 'UNKNOWN' if 'SHIPTOSTREET' in tResultDictionary.keys(): tContext['SHIPTOSTREET'] = tResultDictionary['SHIPTOSTREET'] else: tContext['SHIPTOSTREET'] = 'UNKNOWN' if 'SHIPTOSTREET2' in tResultDictionary.keys(): tContext['SHIPTOSTREET2'] = tResultDictionary['SHIPTOSTREET2'] else: tContext['SHIPTOSTREET2'] = 'UNKNOWN' if 'SHIPTOCITY' in tResultDictionary.keys(): tContext['SHIPTOCITY'] = tResultDictionary['SHIPTOCITY'] else: tContext['SHIPTOCITY'] = 'UNKNOWN' if 'SHIPTOSTATE' in tResultDictionary.keys(): tContext['SHIPTOSTATE'] = tResultDictionary['SHIPTOSTATE'] else: tContext['SHIPTOSTATE'] = 'UNKNOWN' if 'SHIPTOZIP' in tResultDictionary.keys(): tContext['SHIPTOZIP'] = tResultDictionary['SHIPTOZIP'] else: tContext['SHIPTOZIP'] = 'UNKNOWN' if 'SHIPTOCOUNTRYCODE' in tResultDictionary.keys(): tContext['SHIPTOCOUNTRYCODE'] = tResultDictionary['SHIPTOCOUNTRYCODE'] else: tContext['SHIPTOCOUNTRYCODE'] = 'UNKNOWN' if 'SHIPTOPHONENUM' in tResultDictionary.keys(): tContext['SHIPTOPHONENUM'] = tResultDictionary['SHIPTOPHONENUM'] else: tContext['SHIPTOPHONENUM'] = 'UNKNOWN' #Get order amount to add to dated totals tCurrentCost = float(tOrder.orderCost) #Get date 30 days ago tStartDate = tOrder.orderCreated tIncrement = datetime.timedelta(days = -30) tEndDate = tStartDate + tIncrement tCustomerOrderQuery = Order.all() tCustomerOrderQuery.filter("orderCreated >", tEndDate) tCustomerOrderQuery.filter("orderCustomer", tOrder.orderCustomer) tCustomerOrderQuery.filter("orderDeliver", 'True') tCustomerOrders = tCustomerOrderQuery.fetch(1000) #logging.debug("30 day date: " + str(tEndDate)) #logging.debug("30 day orders: " + str(len(tCustomerOrders))) tCustomerOrderTotal = 0.0 for tCustomerOrder in tCustomerOrders: tCustomerOrderTotal += float(tCustomerOrder.orderCost) if (tOrder.orderDeliver == 'False'): tCustomerOrderTotal += tCurrentCost tOrderData['orderTotal'] = str("%.2f"% tCustomerOrderTotal) #Get date 24 hours ago tStartDate = tOrder.orderCreated tIncrement = datetime.timedelta(days = -1) tEndDate = tStartDate + tIncrement tCustomerOrderQuery = Order.all().filter("orderCreated >", tEndDate) tCustomerOrderQuery.filter("orderCustomer", tOrder.orderCustomer) tCustomerOrderQuery.filter("orderDeliver", 'True') tCustomerOrders = tCustomerOrderQuery.fetch(1000) #logging.debug("24 hour date: " + str(tEndDate)) #logging.debug("24 hour orders: " + str(len(tCustomerOrders))) tCustomerOrderTotal24 = 0.0 for tCustomerOrder in tCustomerOrders: tCustomerOrderTotal24 += float(tCustomerOrder.orderCost) if (tOrder.orderDeliver == 'False'): tCustomerOrderTotal24 += tCurrentCost tOrderData['orderTotal24'] = str("%.2f" % tCustomerOrderTotal24) #Get date 15 days ago tStartDate = tOrder.orderCreated tIncrement = datetime.timedelta(days = -15) tEndDate = tStartDate + tIncrement tCustomerOrderQuery = Order.all().filter("orderCreated >", tEndDate) tCustomerOrderQuery.filter("orderCustomer", tOrder.orderCustomer) tCustomerOrderQuery.filter("orderDeliver", 'True') tCustomerOrders = tCustomerOrderQuery.fetch(1000) #logging.debug("15 day date: " + str(tEndDate)) #logging.debug("15 day orders: " + str(len(tCustomerOrders))) tCustomerOrderTotal15 = 0.0 for tCustomerOrder in tCustomerOrders: tCustomerOrderTotal15 += float(tCustomerOrder.orderCost) if (tOrder.orderDeliver == 'False'): tCustomerOrderTotal15 += tCurrentCost tOrderData['orderTotal15'] = str("%.2f" % tCustomerOrderTotal15) #===== Begin Location Matching ===== try: tPhoneHandler = PhoneLookup() tPhoneInfo = tPhoneHandler.GetPhone(tOrder.orderCustomer)[0] except: tPhoneInfo = Phone() tPhoneInfo.phoneState = "Unknown" tPhoneInfo.phoneCountry = "Unknown" #logging.debug("Ip country: " + str(tIpInfo.ipCountry)) #logging.debug("Paypal country: " + str(tPaypalCountry)) if (str(tIpInfo.ipCountry) == str(tPaypalCountry)): tOrderData['locationmatch'] = 'True' else: tOrderData['locationmatch'] = 'False' if (str(tIpInfo.ipCountry) == "United Kingdom" and str(tPaypalCountry) == "Great Britain (UK)"): tOrderData['locationmatch'] = 'True' #Agent Instructions #logging.debug("Order Total 24: " + str(tCustomerOrderTotal24)) #logging.debug("Order Total: " + str(tCustomerOrderTotal)) #logging.debug("Customer email verified: " + str(tCustomer.customerEmailVerified)) #logging.debug("Customer phone verified: " + str(tCustomer.customerPhoneVerified)) #logging.debug("Customer id verified: " + str(tCustomer.customerIdVerified)) #Protection Eligibility Filter tCountryEligibilityCode = tContext['SHIPTOCOUNTRYCODE'] tOrderData['instructions'] = "No verification required" # default value if tCountryEligibilityCode in ('US', 'UK', 'CA', 'GB'): if tOrder.orderCost > 10: if tProtectionEligibility == 'Eligible': if tCustomerOrderTotal24 > 1000.0 or tCustomerOrderTotal > 4000.0: tOrderData['instructions'] = "<span style='color:red'>$$$ Call Corowns $$$</span>" else: # not payment eligible tOrderData['instructions'] = "<span style='color:red'>Refund - No Seller Protection</span>" tContext['tDisplayDeliver'] = 'False' else: # international customer #if( tCustomerOrderTotal24 < 30.0 and tCustomerOrderTotal < 60.0): if tIpInfo.ipType == "Corporate": tOrderData['instructions'] = tOrderData['instructions'] + "<br /><span style='color:red'>Refer to PA - Corporate IP</span>" tOrderData['tDisplayDeliver'] = 'False' if (tIpInfo.ipProxy): if ("Confirmed proxy server" == tIpInfo.ipProxy): tOrderData['instructions'] = tOrderData['instructions'] + "<br /><span style='color:red'>Refer to PA - Proxy</span>" tContext['tDisplaydeliver'] = 'False' if tCustomerOrderTotal24 > 200.0 or tCustomerOrderTotal > 400.0: tOrderData['instructions'] = "<span style='color:red'>Refer to PA - Limit Exceeded</span>" tOrderData['tDisplayDeliver'] = 'False' elif tCustomerOrderTotal24 > 90.0 or tCustomerOrderTotal > 180.0: if tCustomer.customerIdVerified != True: tOrderData['instructions'] = "<span style='color:red'>Verify Photo ID</span>" elif tCustomerOrderTotal24 > 30.0 or tCustomerOrderTotal > 60.0: if tCustomer.customerPhoneVerified != True: tOrderData['instructions'] = "<span style='color:red'>Verify Phone Number</span>" if(tOrderData['locationmatch'] != 'True'): tOrderData['instructions'] = tOrderData['instructions'] + "<br /><span style='color:red'>Verify Country Match</span>" #logging.debug("Order Data Instructions: " + str(tOrderData['instructions'])) #logging.debug("Location Match" + str(tOrderData['locationmatch'])) tCustomerOrderQuery = db.GqlQuery("SELECT * FROM Order WHERE orderCustomer = '" + tOrder.orderCustomer + "'") tTotalCustomerOrders = [] tTotalCustomerOrders = tCustomerOrderQuery.fetch(50) for tCustomerOrder in tTotalCustomerOrders: if (tCustomerOrder.orderChargeback == True): tChargeBack = True else: tChargeBack = False tOrderData['chargeback'] = tChargeBack if (tChargeBack) else False tOrderData['chargeback'] = str(tOrderData['chargeback']) tIpChargebacks = tIpHandler.GetChargebacks(tOrder.orderIp) tOrderData['ipchargeback'] = len(tIpChargebacks) try: tTotalBonusString = NumberToGp.ConvertIntToBet(int(tOrder.orderBonusQuantity)) #logging.debug("Total Bonus String " + tTotalBonusString) except: tTotalBonusString = "" if (tCustomer.customerIsPaBlacklisted == True): tOrderData['instructions'] = tOrderData['instructions'] + "<br /><span style='color:red'>Refer to PA - Blacklist</span>" tContext['tDisplayDeliver'] = 'False' if (tCustomer.customerIsGlobalBlacklisted == True): tOrderData['instructions'] = tOrderData['instructions'] + "<br /><span style='color:red'>Do Not Deliver - Blacklist</span>" tContext['tDisplayDeliver'] = 'False' #normalize unicode try: tSimpleGold = unicodedata.normalize("NFC", tOrder.orderSimpleGoldAmount).encode("ascii", "ignore") except: tSimpleGold = tOrder.orderSimpleGoldAmount #logging.debug(str(tPriceDic[tSimpleGold])) #logging.debug(str(tOrder.orderCost)) tCurrentEocPrices = PriceContainer.GetCurrentPriceDic() tCurrent07Prices = PriceContainer.GetCurrentPriceDic07() #logging.debug(str(tCurrent07Prices)) #logging.debug(str(tCurrentEocPrices)) tSkip07 = False tValidOrder = False if tOrder.orderSimpleGoldAmount in tCurrentEocPrices.keys(): if str(tOrder.orderCost) == str(tCurrentEocPrices[tOrder.orderSimpleGoldAmount]): tOrder.orderGoldType = 'eoc' tSkip07 = True tValidOrder = True if not tSkip07: if tOrder.orderSimpleGoldAmount in tCurrent07Prices.keys(): if str(tOrder.orderCost) == str(tCurrent07Prices[tOrder.orderSimpleGoldAmount]): tOrder.orderGoldType = '07' tValidOrder = True #logging.debug("skip07 {}".format(tSkip07)) #logging.debug("valid {}".format(tValidOrder)) #logging.debug("order simple gold amount {}".format(tOrder.orderSimpleGoldAmount)) #logging.debug("order value {}".format(tOrderData['orderTotal'])) #logging.debug("gold type {}".format(tContext['gold_type'])) if not tValidOrder: tOrderData['instructions'] = tOrderData['instructions'] + '<br /><span style="color:red">Do Not Deliver - Bad Payment</span>' #tOrderData['tDisplayDeliver'] = 'False' #tOrder.orderLocked = 'True' #tOrder.put() #logging.debug(str(tOrder.orderIsGenerated)) if(tOrder.orderIsGenerated == True): tOrder.orderLocked = 'False' tOrder.orderIsRefunded = 'False' tOrder.orderDeliver = 'False' tOrderData['tDisplayDeliver'] = 'True' try: tDeliveryAgent = Agent.GetAgentByEmail(tOrder.orderDeliveryAgent) tContext['tDeliveryAgent'] = tDeliveryAgent except: pass try: tAssignedAgent = Agent.GetAgentByEmail(tOrder.orderAssignedAgent) tContext['tAssignedAgent'] = tAssignedAgent except: pass try: tRefundAgent = Agent.GetAgentByEmail(tOrder.orderRefundAgent) tContext['tRefundAgent'] = tRefundAgent except: pass tOrderData['bonus'] = tTotalBonusString tOrderData['phoneverified'] = str(tCustomer.customerPhoneVerified) tOrderData['emailverified'] = str(tCustomer.customerEmailVerified) tOrderData['idverified'] = str(tCustomer.customerIdVerified) tContext['tOrder'] = tOrder tContext['tOrderData'] = tOrderData tContext['tCustomer'] = tCustomer tContext['tIpInfo'] = tIpInfo tContext['tPhoneInfo'] = tPhoneInfo if ((tOrder.orderDeliveryAgent == "" or tOrder.orderDeliveryAgent == None) and tOrder.orderDeliver == 'True'): tAgentKey = tOrder.orderAgent tAgentId = Agent() tAgentId = Agent.get(tAgentKey) tOrder.orderDeliveryAgent = str(tAgentId.agentId) #logging.debug(str(tOrderData)) return tContext