def GetContext(self): tContext = {} if (self.IsUserAdmin()): tAgentsQuery = Agent().all() tAgentsQuery.order("agentNickName") tAgentsQuery.filter("agentIsEnabled", True) tAgents = tAgentsQuery.fetch(100) tAgent = Agent() for tAgent in tAgents: tAgent.__setattr__( 'agentGoldSupplyEocString', NumberToGp.ConvertIntToBet(tAgent.agentGoldSupplyEoc)) tAgent.__setattr__( 'agentGoldSupply07String', NumberToGp.ConvertIntToBet(tAgent.agentGoldSupply07)) tContext['agents'] = tAgents return tContext else: self.redirect("/")
def post(self): from models.order import Order from _numbertogp import NumberToGp tCalc = CalcReferral() tOrderKey = self.request.get('key') tOrder = Order() tOrder = Order.get(str(tOrderKey)) tReferCode = tOrder.orderReferralCode if (tReferCode == None): tReferCode = "" #logging.debug("Referrer Code: " + tReferCode) if (tReferCode == "" or tReferCode == None): return None tRefererQuery = Referrer.all() tRefererQuery.filter('referId', tReferCode) tReferer = Referrer() try: tReferer = tRefererQuery.fetch(1)[0] except: #logging.debug("Referrer Code Not Found: " + tReferCode) return None tGp = 0.0 tCash = 0.0 #No matching referrers and paypal emails if(tReferer.referEmail != None): if(str(tReferer.referEmail).lower() == str(tOrder.orderPaypalEmail).lower()): return None if (tReferer.referGp == 0.0 or tReferer.referCash == 0.0): tGp = tOrder.orderQuantity * 0.2 tCash = tOrder.orderCost * 0.2 else: tGp = float(tReferer.referGp) + (tOrder.orderQuantity * 0.1) tCash = float(tReferer.referCash) + (tOrder.orderCost * 0.1) tReferer.referGp = tGp tReferer.referCash = tCash tReferer.referSimpleGold = NumberToGp.ConvertIntToBet(int(float(tGp))) tReferer.referSimpleCash = tCalc.FormatCurrency(tCash) #logging.debug("Referrer Gp: " + str(tGp)) #logging.debug("Referrer Cash: " + str(tCash)) #logging.debug("Referrer Simple Gold: " + str(tReferer.referSimpleGold)) #logging.debug("Referrer Simple Cash: " + str(tReferer.referSimpleCash)) tReferer.put()
def receive(self, mail_message): #logging.debug("Received a message from: " + PaOrderHandler.unwraptext(mail_message.sender)) #logging.debug("Subject: " + PaOrderHandler.unwraptext(mail_message.subject)) for bodies in mail_message.bodies('text/plain'): emailtext = "" for body in bodies: try: encodedtext = body[1] emailtext = PaOrderHandler.unwraptext(encodedtext) except: emailtext = body.payload.decode(body.encoding) if (isinstance(emailtext, unicode)): emailtext = emailtext.encode('utf-8') #logging.debug("Body PlainText: " + emailtext) OrderAmountText = self.reOrder.search( emailtext).groupdict()['order'].strip() OrderAmountInt = NumberToGp.ConvertBetToInt(OrderAmountText) OrderId = self.reOrderId.search( emailtext).groupdict()['orderid'].strip() tMatchingOrderQuery = PaOrder.all() tMatchingOrderQuery.filter("paTransactionId", OrderId) tMatches = tMatchingOrderQuery.fetch(10) if (len(tMatches) > 0): return tPaOrder = PaOrder() tPaOrder.paAmount = OrderAmountText tPaOrder.paAmountInt = OrderAmountInt tPaOrder.paTransactionId = OrderId tAssignedAgentClass = DeliveryAssignment() tAssignedAgent = tAssignedAgentClass.GetAssignedAgent() if (tAssignedAgent != 'No Agent Online'): tPaOrder.paAssignedAgent = tAssignedAgent.agentId tPaOrder.paAssignedAgentNick = tAssignedAgent.agentNickName else: tPaOrder.paAssignedAgent = "No Agent Online" tPaOrder.paAssignedAgentNick = "No Agent Online" tPaOrder.put()
def post(self): tPaypalEmail = self.request.get('email') tCustomerName = self.request.get('name') tGoldAmount = self.request.get('gold') tOrderKey = self.request.get('key') tOrder = Order() tOrder = Order.get(tOrderKey) tVerificationCode = tOrder.orderVerificationCode tGoldInt = int(tGoldAmount.split('.')[0]) logging.debug("Gold Int: " + str(tGoldInt)) tGoldAmount = NumberToGp.ConvertIntToBet(tGoldInt) #logging.debug("Customer Name " + str(tCustomerName)) #logging.debug("Gold Amount " + str(tGoldAmount)) tMessage = """ Dear %s, Thank you for choosing the eMeMO SmokinShop. We have received your payment for a code redeemable for %s. If you were not automatically returned to our website after payment, please go to http://smokinshop.com/delivery.php and speak to an eMeMO agent in the live chat. Your unique verification code is %s. You will also find your code attached to this email in a text file. Please speak to an eMeMO agent or visit http://smokinshop.com/delivery.php to activate your code and redeem it for RuneScape GP. Regards, The eMeMO Team """ % (str(tCustomerName), str(tGoldAmount), str(tVerificationCode)) logging.debug(str(tMessage)) message = mail.EmailMessage() message.sender = "eMeMO SmokinShop Support<*****@*****.**>" message.to = tPaypalEmail message.subject = "eMeMO SmokinShop Order Details" message.body = tMessage message.cc = "*****@*****.**" message.attachments = [('verification-code.txt', tVerificationCode)] message.send()
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 PostContext(self): tNewOrder = ManualPaOrder() tAgent = Agent() tPromo = Promo() tUserEmail = self.GetUser().email() tStockAccount = StockAccount() tStockManager = StockManager() tStockManager.LoadAccounts() tAgent = Agent().GetAgentByEmail(tUserEmail) logging.debug('Agent ' + str(tAgent.agentNickName)) tPromoCode = self.request.get('promocode').lower().lstrip().rstrip() tPromoCode = tPromoCode.lower().lstrip().rstrip() tGoldType = str(self.request.get('type')).lower().lstrip().rstrip() tGoldAmountWeb = str(self.request.get('amount')).lower() tGoldAmountPretty = re.sub(r'[^0-9kmb]*','', tGoldAmountWeb) tGoldMatches = re.match(r'^[0-9]*(k|m|b{1})$', tGoldAmountPretty) if tGoldMatches is None: return {'error' : str(tGoldAmountWeb) + ' is an invalid gold amount'} tGoldValue = str(self.request.get('value')).lower() tGoldValue = float(re.sub(r'[^0-9\.*]*', '', tGoldValue)) tPaId = self.request.get('paid').lower().lstrip().rstrip() if (tGoldType in ('eoc', '07')) is not True: return {'error' : str(tGoldType) + ' is an invalid gold type' } if not tGoldValue >= 0.0: return {'error' : str(tGoldValue) + ' is an invalid gold value'} tStringOffset = self.request.get('offset') if (len(tStringOffset) > 0): tOffset = int(tStringOffset) else: tOffset = 0 tNewOrder.orderOwner = tUserEmail tGoldAmount = NumberToGp.ConvertBetToInt(tGoldAmountPretty) tUsedBonus = [] try: #logging.debug("Promo Code: " + str(tPromoCode)) tPromo = Promo.GetPromoByCode(tPromoCode) #logging.debug("Promo: " + str(tPromo)) #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)) tPromoGoldAmount = int(tTotalBonusFloat) #logging.debug("Total Bonus Float " + str(tTotalBonusFloat)) #logging.debug("Promo Gold Amount " + str(tPromo.promoGoldAmount)) #logging.debug("Promo Percentage " + str(tPercentBonus)) except: tPromoGoldAmount = 0 tOrderTotalAmount = int(tGoldAmount) + int(tPromoGoldAmount) #logging.debug('Order gold ' + str(tOrderTotalAmount)) logging.debug("{}".format(tOrderTotalAmount)) logging.debug("{}".format(tGoldType)) tStockManager.PlaceOrder(tOrderTotalAmount * -1, tGoldType) #if tGoldType == '07': ##logging.debug('07 detected') #tStockManager.PlaceOrder(aGoldQua #tStockAccountManager.Set07Stock(int(tOrderTotalAmount * -1)) ##tAgent.agentGoldSupply07 = int(tAgent.agentGoldSupply07) - tOrderTotalAmount #elif tGoldType == 'eoc': ##logging.debug('eoc detected') ##tStockAccountManager.SetEOCStock(int(tOrderTotalAmount * -1)) ##tAgent.agentGoldSupplyEoc = int(tAgent.agentGoldSupplyEoc) - tOrderTotalAmount #logging.debug('Agent 07 ' + str(tAgent.agentGoldSupply07)) #logging.debug('Agent eoc ' + str(tAgent.agentGoldSupplyEoc)) tCommission = float(tGoldValue) * 0.05 + 0.50 if tCommission >= 10.0: tCommission = 10.0 tNewOrder.orderCashValue = float(tGoldValue) tNewOrder.orderOwner = tUserEmail tNewOrder.orderGoldAmount = int(tGoldAmount) tNewOrder.orderGoldAmountPretty = tGoldAmountPretty tNewOrder.orderGoldType = tGoldType tNewOrder.orderPaId = tPaId tNewOrder.orderPromoCode = tPromoCode tNewOrder.orderPromoGoldAmount = tPromoGoldAmount tNewOrderGuid = tNewOrder.put() tAgent.agentCurrentCommission = float(tAgent.agentCurrentCommission + tCommission) tAgent.agentTotalCommission = float(tAgent.agentTotalCommission + tCommission) tAgent.agentManualPaOrders = tAgent.agentManualPaOrders + [str(tNewOrderGuid)] tAgent.put() if int(tOffset) > 0: self.LOCATION = '/palist?offset=' + str(tOffset) else: self.LOCATION = '/palist' self.REDIRECT = True return {}
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