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 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
Exemplo n.º 3
0
    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