Exemple #1
0
	def post( self ):
		""" Handles HTTP POST requests. """
		Promo(code=Promo.generate_code()).put()
		
		query = Promo.all()
		query.filter('used =', False)
		promos = query.fetch(250)
		
		options = self.get_options()
		options["promos"] = promos
		options["content"] = self.render( "admin/promos.html", options )
		self.response.out.write( self.render( "admin.html", options ) )
Exemple #2
0
	def get( self ):
		""" Handles HTTP GET requests. """
		query = Promo.all()
		query.filter('used =', False)
		promos = query.fetch(250)
		
		options = self.get_options()
		options["promos"] = promos
		options["content"] = self.render( "admin/promos.html", options )
		self.response.out.write( self.render( "admin.html", options ) )
    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 post(self):
     tOrderKey = self.request.get('orderid')
     tAgentGold = self.request.get('agentgold')
     
     #logging.debug("tOrderKey: " + tOrderKey)
     #logging.debug("tAgentGold: " + tAgentGold)
     tOrder = Order()
     tOrder = Order.get(tOrderKey)
     tUser = users.get_current_user()
     tAgent = Agent().GetAgentByEmail(str(tUser.email()))
     
     if (tOrder.orderDeliver == "" or tOrder.orderDeliver == 'False' and tOrder.orderLocked != 'True' and tAgent.agentIsEnabled == True):
             
         tGoldAmount = tOrder.orderQuantity
         tPromoCode = ""
         tPromoCode = tOrder.orderPromotionalCode
         tPromo = Promo()
         tPromoCode = tPromoCode.lower()
         tReferCode = tOrder.orderReferralCode
         tCustomerLookup = CustomerHandler()
         tCustomer = Customer()
         
         tCustomer = Customer().get(str(tOrder.orderCustomer))
         # Promo codes get unlimited uses per customer
         # tUsedBonus = Order.GetCustomerPromoCodes(tCustomer.customerPaypalId)
         # tUsedBonus = tCustomer.customerUsedBonus
         # logging.debug("Customer used bonuses: " + str(tUsedBonus))
         # logging.debug("Order Promo Code: " + str(tPromoCode))
         tUsedBonus = [] 
         
         try:
             tPromo = Promo.GetPromoByCode(tPromoCode)
             # logging.debug(str(tPromo.promoGoldAmount))
             # logging.debug(str(tPromo.promoPercentage))
             # logging.debug(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 = float(tGoldAmount) * tPromo.promoPercentage
                     #tUsedBonus.append(tPromoCode)
                     
                 tGoldAmount = tGoldAmount + tPercentBonus
                 tGoldAmount = tGoldAmount + tPromo.promoGoldAmount
                 tTotalBonusFloat = tPercentBonus + tPromo.promoGoldAmount
                 tOrder.orderBonusQuantity = int(tTotalBonusFloat)     
         except:
             tOrder.orderBonusQuantity = 0
             
         tGoldAmountLong = tGoldAmount
         tGoldAmount = tGoldAmount / 1000000
         
         tOrderValue = float(tOrder.orderCost)
         
         #if(tOrder.orderIsGenerated == True):
             #tGoldAmountLong = 0
             #tGoldAmount = 0
         
             
         tStockManager = StockManager()
         tStockManager.LoadAccounts()            
         tStockManager.PlaceOrder(tGoldAmountLong * -1, tOrder.orderGoldType)            
                         
         #if tOrder.orderGoldType == '07':
             #tStockAccountManager.Set07Stock(int(tGoldAmountLong * -1))
         #else:
             #tStockAccountManager.SetEOCStock(int(tGoldAmountLong * -1))
                         
         tCommission = float(tOrderValue) * 0.05 + 0.50
         
         if tCommission >= 10.0:
             tCommission = 10.0                           
             
         tAgent.agentCurrentCommission = float(tAgent.agentCurrentCommission + tCommission)
         tAgent.agentTotalCommission = float(tAgent.agentTotalCommission + tCommission)                
         
         tAgentOrders = tAgent.agentOrders
         tAgentOrders.append(tOrderKey)
         tAgent.agentOrders = tAgentOrders
         tAgentKey = tAgent.put()
         tOrder.orderDeliveryAgent = str(tAgent.agentId)
         tOrder.orderAgent = str(tAgentKey)
         tOrder.orderDeliver = 'True'
         tKey = tOrder.put()
         
         #logging.debug("Delivery by Agent: " + str(tAgentKey))
         #logging.debug("Delivery of Order: " + str(tKey))
         
         #taskqueue.add(url='/calcreferral', countdown = 1, params={'key' : str(tKey) } )
         
         self.response.headers['Cache-Control'] = 'Cache-Control: no-cache, must-revalidate'
         self.response.headers['Content-Type'] = 'Content-Type: plain/text'
         self.response.out.write("Order Delivered")
     else:
         #logging.debug('Attempted to Deliver ' + tOrderKey + " by Agent " + tAgent.agentId)
         self.response.headers['Cache-Control'] = 'Cache-Control: no-cache, must-revalidate'
         self.response.headers['Content-Type'] = 'Content-Type: plain/text'
         self.response.out.write("Order Not Deliverable")
    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 {} 
     
     
     
     
     
     
     
     
     
     
     
Exemple #7
0
    def post(self):
        tOrderKey = self.request.get('orderid')
        tAgentGold = self.request.get('agentgold')

        #logging.debug("tOrderKey: " + tOrderKey)
        #logging.debug("tAgentGold: " + tAgentGold)
        tOrder = Order()
        tOrder = Order.get(tOrderKey)
        tUser = users.get_current_user()
        tAgent = Agent().GetAgentByEmail(str(tUser.email()))

        if (tOrder.orderDeliver == "" or tOrder.orderDeliver == 'False'
                and tOrder.orderLocked != 'True'
                and tAgent.agentIsEnabled == True):

            tGoldAmount = tOrder.orderQuantity
            tPromoCode = ""
            tPromoCode = tOrder.orderPromotionalCode
            tPromo = Promo()
            tPromoCode = tPromoCode.lower()
            tReferCode = tOrder.orderReferralCode
            tCustomerLookup = CustomerHandler()
            tCustomer = Customer()

            tCustomer = Customer().get(str(tOrder.orderCustomer))
            # Promo codes get unlimited uses per customer
            # tUsedBonus = Order.GetCustomerPromoCodes(tCustomer.customerPaypalId)
            # tUsedBonus = tCustomer.customerUsedBonus
            # logging.debug("Customer used bonuses: " + str(tUsedBonus))
            # logging.debug("Order Promo Code: " + str(tPromoCode))
            tUsedBonus = []

            try:
                tPromo = Promo.GetPromoByCode(tPromoCode)
                # logging.debug(str(tPromo.promoGoldAmount))
                # logging.debug(str(tPromo.promoPercentage))
                # logging.debug(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 = float(
                            tGoldAmount) * tPromo.promoPercentage
                        #tUsedBonus.append(tPromoCode)

                    tGoldAmount = tGoldAmount + tPercentBonus
                    tGoldAmount = tGoldAmount + tPromo.promoGoldAmount
                    tTotalBonusFloat = tPercentBonus + tPromo.promoGoldAmount
                    tOrder.orderBonusQuantity = int(tTotalBonusFloat)
            except:
                tOrder.orderBonusQuantity = 0

            tGoldAmountLong = tGoldAmount
            tGoldAmount = tGoldAmount / 1000000

            tOrderValue = float(tOrder.orderCost)

            #if(tOrder.orderIsGenerated == True):
            #tGoldAmountLong = 0
            #tGoldAmount = 0

            tStockManager = StockManager()
            tStockManager.LoadAccounts()
            tStockManager.PlaceOrder(tGoldAmountLong * -1,
                                     tOrder.orderGoldType)

            #if tOrder.orderGoldType == '07':
            #tStockAccountManager.Set07Stock(int(tGoldAmountLong * -1))
            #else:
            #tStockAccountManager.SetEOCStock(int(tGoldAmountLong * -1))

            tCommission = float(tOrderValue) * 0.05 + 0.50

            if tCommission >= 10.0:
                tCommission = 10.0

            tAgent.agentCurrentCommission = float(
                tAgent.agentCurrentCommission + tCommission)
            tAgent.agentTotalCommission = float(tAgent.agentTotalCommission +
                                                tCommission)

            tAgentOrders = tAgent.agentOrders
            tAgentOrders.append(tOrderKey)
            tAgent.agentOrders = tAgentOrders
            tAgentKey = tAgent.put()
            tOrder.orderDeliveryAgent = str(tAgent.agentId)
            tOrder.orderAgent = str(tAgentKey)
            tOrder.orderDeliver = 'True'
            tKey = tOrder.put()

            #logging.debug("Delivery by Agent: " + str(tAgentKey))
            #logging.debug("Delivery of Order: " + str(tKey))

            #taskqueue.add(url='/calcreferral', countdown = 1, params={'key' : str(tKey) } )

            self.response.headers[
                'Cache-Control'] = 'Cache-Control: no-cache, must-revalidate'
            self.response.headers['Content-Type'] = 'Content-Type: plain/text'
            self.response.out.write("Order Delivered")
        else:
            #logging.debug('Attempted to Deliver ' + tOrderKey + " by Agent " + tAgent.agentId)
            self.response.headers[
                'Cache-Control'] = 'Cache-Control: no-cache, must-revalidate'
            self.response.headers['Content-Type'] = 'Content-Type: plain/text'
            self.response.out.write("Order Not Deliverable")