def GetContext(self): tAgent = Agent() tAgentList = [] tAgentOrders = [] tAgentDonations = [] tAgentRequest = self.request.get('agent') context = {} tAgentList = Agent.all() context['agents'] = tAgentList if (tAgentRequest != ""): tAgent = Agent.get(tAgentRequest) tAgentOrdersQuery = Order.all() tAgentOrdersQuery.filter('orderAgent', str(tAgentRequest)) tAgentOrdersQuery.order('-orderCompleted') tAgentOrders = tAgentOrdersQuery.fetch(100) tAgentDonorsQuery = DonorRecord.all() tAgentDonorsQuery.filter('donorAgent', tAgent.agentId) tAgentDonorsQuery.order('-donorDate') tAgentDonations = tAgentDonorsQuery.fetch(100) #logging.debug("Agent Order Count: " + str(len(tAgentOrders))) #logging.debug("Agent Donation Count: " + str(len(tAgentDonations))) context['agent'] = tAgent context['orders'] = tAgentOrders context['donations'] = tAgentDonations context['extended'] = 'True' return context
def order_list(): u = current_user() ms = Order.all() ms.reverse() for m in ms: m.user = User.get(m.user_id) m.ct = time_str(m.ct) return render_template('admin_order.html', ms=ms, u=u)
def GetContext(self): tContext = {} tOrderQuery = Order.all() tOrderQuery.filter("orderDeliver", "False") tOrderQuery.order("orderCreated") tOrderList = tOrderQuery.fetch(500) tContext['orders'] = tOrderList return tContext
def get(self): path = os.path.join(os.path.dirname(__file__), '../views/orders/index.html') template_values = { 'name': self.__class__.__name__, 'orders': Order.all().order('-createdOn'), } self.response.out.write(template.render(path, template_values))
def post(self): tUrl = "https://api-3t.paypal.com/nvp" tPaypalPayload = {} tPaypal = PaypalRefund() tAgent = Agent() tOrder = Order() tUser = users.get_current_user() tTransId = str(self.request.get('orderid')) tAgentEmail = str(tUser.email()) tAgent = Agent().GetAgentByEmail(tAgentEmail) tRefundAgent = tAgentEmail tOrderQuery = Order.all() tOrderQuery.filter("orderTransactionId", tTransId) #logging.debug("Transaction id: " + tTransId) tOrder = tOrderQuery.get() if (tOrder.orderDeliver != 'True'): tPaypalPayload['METHOD'] = "RefundTransaction" tPaypalPayload['TRANSACTIONID'] = tTransId tPayloadEncoded = tPaypal.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) #logging.debug("Mechanize Package") #logging.debug("Url: " + tUrl) #logging.debug("Data: " + str(tPaypalPayload)) tResult = tResponse.read() #logging.debug(tResult) tOrder.orderIsRefunded = "True" tOrder.orderRefundAgent = tRefundAgent tOrder.orderLocked = "True" tOrder.orderRefundId = "" tOrder.put() self.response.out.write("Order Locked and Refunded")
def douban_order(): if not (g.user.is_super_leader() or g.user.is_contract() or g.user.is_finance()): abort(403) location = int(request.values.get('location', 0)) now_date = datetime.datetime.now() year = int(request.values.get('year', now_date.year)) # 获取整年月份 pre_year_month = get_monthes_pre_days(datetime.datetime.strptime(str(year) + '-01', '%Y-%m'), datetime.datetime.strptime(str(year) + '-12', '%Y-%m')) # 获取所有回款包含返点发票 back_money_data = _all_douban_order_back_moneys() client_back_money_data = _all_client_order_back_moneys() # 获取当年豆瓣合同 orders = DoubanOrder.query.filter(DoubanOrder.status == 1, DoubanOrder.contract != '') # 获取当前执行年合同 if location: orders = [k for k in orders if (k.client_start.year == year or k.client_end.year == year) and location in k.locations] else: orders = [k for k in orders if k.client_start.year == year or k.client_end.year == year] # 格式化合同 orders = [_douban_order_to_dict(k, back_money_data, pre_year_month, location ) for k in orders] # 获取豆瓣合同结束 orders = [k for k in orders if k['contract_status'] in [2, 4, 5, 10, 19, 20]] # 获取关联豆瓣合同 medium_orders = [_medium_order_to_dict(k, client_back_money_data, pre_year_month, location) for k in Order.all() if (k.medium_start.year == year or k.medium_end.year == year) and k.associated_douban_order] if location: orders += [k for k in medium_orders if k['contract_status'] in [2, 4, 5, 10, 19, 20] and k['status'] == 1 and location in k['locations']] else: orders += [k for k in medium_orders if k['contract_status'] in [2, 4, 5, 10, 19, 20] and k['status'] == 1] # 获取关联豆瓣合同结束 orders = sorted( orders, key=operator.itemgetter('start_date_cn'), reverse=False) total_money_data = [0 for k in range(12)] for k in orders: total_money_data = numpy.array( total_money_data) + numpy.array(k['money_data']) if request.values.get('action') == 'excel': return write_order_excel(orders, year, total_money_data, location, 'douban_order') return tpl('/data_query/accrued/douban_order.html', orders=orders, year=year, total_money_data=total_money_data, location=location)
def get_orders(): l = Order.all() l = [o.json() for o in l] l.reverse() for order in l: r = [] for id, q in order['items'].items(): # log(id, q) title = Book.get(int(id)).title r.append({ 'title': title, 'quantity': q, }) order['items'] = r order['time'] = datetime.datetime.fromtimestamp(order['ct']).strftime("%Y-%m-%d %H:%M:%S") return json_response(l)
def post(self): tUrl = "https://api-3t.paypal.com/nvp" tPaypalPayload = {} tPaypal = PaypalRefund() tAgent = Agent() tOrder = Order() tUser = users.get_current_user() tTransId = str(self.request.get("orderid")) tAgentEmail = str(tUser.email()) tAgent = Agent().GetAgentByEmail(tAgentEmail) tRefundAgent = tAgentEmail tOrderQuery = Order.all() tOrderQuery.filter("orderTransactionId", tTransId) # logging.debug("Transaction id: " + tTransId) tOrder = tOrderQuery.get() if tOrder.orderDeliver != "True": tPaypalPayload["METHOD"] = "RefundTransaction" tPaypalPayload["TRANSACTIONID"] = tTransId tPayloadEncoded = tPaypal.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) # logging.debug("Mechanize Package") # logging.debug("Url: " + tUrl) # logging.debug("Data: " + str(tPaypalPayload)) tResult = tResponse.read() # logging.debug(tResult) tOrder.orderIsRefunded = "True" tOrder.orderRefundAgent = tRefundAgent tOrder.orderLocked = "True" tOrder.orderRefundId = "" tOrder.put() self.response.out.write("Order Locked and Refunded")
def order(): sn = request.values.get('sn', '') client_order = [ _order_to_dict(k) for k in ClientOrder.all() if k.contract.lower().strip() == sn.lower().strip() ] douban_order = [ _order_to_dict(k) for k in DoubanOrder.all() if k.contract.lower().strip() == sn.lower().strip() ] client_order += [ _order_to_dict(k.client_order) for k in Order.all() if k.medium_contract.lower().strip() == sn.lower().strip() ] client_order += [ _order_to_dict(k.client_order, k) for k in AssociatedDoubanOrder.all() if k.contract.lower().strip() == sn.lower().strip() ] if client_order: return jsonify({'ret': True, 'data': client_order[0]}) elif douban_order: return jsonify({'ret': True, 'data': douban_order[0]}) else: return jsonify({'ret': False, 'data': {}})
def index(): if not (g.user.is_super_leader() or g.user.is_aduit() or g.user.is_finance() or g.user.is_contract()): abort(403) shenji = int(request.values.get('shenji', 0)) now_date = datetime.datetime.now() year = int(request.values.get('year', now_date.year)) # 获取整年月份 pre_year_month = get_monthes_pre_days( datetime.datetime.strptime(str(year) + '-01', '%Y-%m'), datetime.datetime.strptime(str(year) + '-12', '%Y-%m')) # 获取所有回款包含返点发票 back_money_data = _all_douban_order_back_moneys() client_back_money_data = _all_client_order_back_moneys() # 获取代理返点系数 all_agent_rebate = _all_agent_rebate() # 获取所有外包 all_outsource_data = _all_douban_order_outsource() # 获取当年豆瓣合同 orders = DoubanOrder.query.filter(DoubanOrder.status == 1, DoubanOrder.contract != '') # 去重合同 orders = [ k for k in orders if k.client_start.year == year or k.client_end.year == year ] # 格式化合同 orders = [ _douban_order_to_dict(k, back_money_data, all_agent_rebate, pre_year_month, all_outsource_data, shenji) for k in orders ] # 获取豆瓣合同结束 orders = [ k for k in orders if k['contract_status'] in [2, 4, 5, 10, 19, 20] ] # 获取关联豆瓣合同 medium_orders = [ _medium_order_to_dict(k, client_back_money_data, all_agent_rebate, pre_year_month, all_outsource_data, shenji) for k in Order.all() if (k.medium_start.year == year or k.medium_end.year == year) and k.associated_douban_order ] orders += [ k for k in medium_orders if k['contract_status'] in [2, 4, 5, 10, 19, 20] and k['status'] == 1 ] # 获取关联豆瓣合同结束 orders = sorted(orders, key=operator.itemgetter('start_date_cn'), reverse=False) total_outsource_data = [0 for k in range(12)] total_money_data = [0 for k in range(12)] total_money_rebate_data = [0 for k in range(12)] total_profit_data = [0 for k in range(12)] for k in orders: total_money_data = numpy.array(total_money_data) + numpy.array( k['money_data']) total_outsource_data = numpy.array(total_outsource_data) + numpy.array( k['outsource_data']) total_money_rebate_data = numpy.array( total_money_rebate_data) + numpy.array(k['money_rebate_data']) total_profit_data = numpy.array(total_profit_data) + numpy.array( k['profit_data']) if request.values.get('action') == 'excel': return write_douban_order_excel( orders=orders, year=year, total_money_data=total_money_data, total_money_rebate_data=total_money_rebate_data, total_profit_data=total_profit_data, total_outsource_data=total_outsource_data, shenji=shenji) if shenji: tpl_html = '/shenji/cost_income_douban_order_s.html' else: tpl_html = '/shenji/cost_income_douban_order.html' return tpl(tpl_html, orders=orders, year=year, total_money_data=total_money_data, total_money_rebate_data=total_money_rebate_data, total_outsource_data=total_outsource_data, total_profit_data=total_profit_data)
def index(): query_type = int(request.args.get('query_type', 4)) query_month = request.args.get('query_month', '') page = int(request.args.get('page', 1)) if query_month: query_month = datetime.datetime.strptime(query_month, '%Y-%m') else: query_month = datetime.datetime.strptime( datetime.datetime.now().strftime('%Y-%m'), '%Y-%m') # 全部客户订单 if query_type == 1: query_orders = [ o for o in ClientOrder.all() if o.client_end.strftime('%Y-%m') >= query_month.strftime('%Y-%m') and o.contract_status in ECPM_CONTRACT_STATUS_LIST ] orders = [{ 'agent_name': o.agent.name, 'client_name': o.client.name, 'campaign': o.campaign, 'start': o.client_start, 'end': o.client_end, 'money': o.money } for o in query_orders] # 全部媒体订单 elif query_type == 2: query_orders = [ o for o in Order.all() if o.medium_end.strftime('%Y-%m') >= query_month.strftime('%Y-%m') and o.contract_status in ECPM_CONTRACT_STATUS_LIST ] orders = [{ 'medium_name': o.medium.name, 'campaign': o.campaign, 'start': o.medium_start, 'end': o.medium_end, 'money': o.medium_money } for o in query_orders] # 全部关联豆瓣订单 elif query_type == 3: query_orders = [ o for o in AssociatedDoubanOrder.all() if o.end_date.strftime('%Y-%m') >= query_month.strftime('%Y-%m') and o.contract_status in ECPM_CONTRACT_STATUS_LIST ] orders = [{ 'jiafang_name': o.jiafang_name, 'client_name': o.client.name, 'campaign': o.campaign, 'start': o.start_date, 'end': o.end_date, 'money': o.money } for o in query_orders] # 全部直签豆瓣订单 else: query_orders = [ o for o in DoubanOrder.all() if o.client_end.strftime('%Y-%m') >= query_month.strftime('%Y-%m') and o.contract_status in ECPM_CONTRACT_STATUS_LIST ] orders = [{ 'agent_name': o.agent.name, 'client_name': o.client.name, 'campaign': o.campaign, 'start': o.client_start, 'end': o.client_end, 'money': o.money } for o in query_orders] th_count = 0 th_obj = [] for order in orders: if order['money']: pre_money = float(order['money']) / \ ((order['end'] - order['start']).days + 1) else: pre_money = 0 monthes_pre_days = get_monthes_pre_days( query_month, datetime.datetime.fromordinal(order['start'].toordinal()), datetime.datetime.fromordinal(order['end'].toordinal())) order['order_pre_money'] = [{ 'month': k['month'].strftime('%Y-%m'), 'money': '%.2f' % (pre_money * k['days']) } for k in monthes_pre_days] if len(monthes_pre_days) > th_count: th_obj = [{ 'month': k['month'].strftime('%Y-%m') } for k in monthes_pre_days] th_count = len(monthes_pre_days) if 'excel' == request.args.get('extype', ''): if query_type == 1: filename = ( "%s-%s.xls" % (u"月度客户订单金额", datetime.datetime.now().strftime('%Y%m%d%H%M%S')) ).encode('utf-8') elif query_type == 2: filename = ( "%s-%s.xls" % (u"月度媒体订单金额", datetime.datetime.now().strftime('%Y%m%d%H%M%S')) ).encode('utf-8') elif query_type == 3: filename = ("%s-%s.xls" % (u"月度关联豆瓣订单金额", datetime.datetime.now().strftime('%Y%m%d%H%M%S')) ).encode('utf-8') else: filename = ("%s-%s.xls" % (u"月度直签豆瓣订单金额", datetime.datetime.now().strftime('%Y%m%d%H%M%S')) ).encode('utf-8') xls = write_excel(orders, query_type, th_obj) response = get_download_response(xls, filename) return response return tpl('/data_query/order/index.html', orders=orders, page=page, query_type=query_type, query_month=query_month.strftime('%Y-%m'), th_obj=th_obj)
def index(): query_type = int(request.args.get('query_type', 4)) query_month = request.args.get('query_month', '') page = int(request.args.get('page', 1)) if query_month: query_month = datetime.datetime.strptime(query_month, '%Y-%m') else: query_month = datetime.datetime.strptime( datetime.datetime.now().strftime('%Y-%m'), '%Y-%m') # 全部客户订单 if query_type == 1: query_orders = [o for o in ClientOrder.all() if o.client_end.strftime('%Y-%m') >= query_month.strftime('%Y-%m') and o.contract_status in ECPM_CONTRACT_STATUS_LIST] orders = [{'agent_name': o.agent.name, 'client_name': o.client.name, 'campaign': o.campaign, 'start': o.client_start, 'end': o.client_end, 'money': o.money} for o in query_orders] # 全部媒体订单 elif query_type == 2: query_orders = [o for o in Order.all() if o.medium_end.strftime('%Y-%m') >= query_month.strftime('%Y-%m') and o.contract_status in ECPM_CONTRACT_STATUS_LIST] orders = [{'medium_name': o.medium.name, 'campaign': o.campaign, 'start': o.medium_start, 'end': o.medium_end, 'money': o.medium_money} for o in query_orders] # 全部关联豆瓣订单 elif query_type == 3: query_orders = [o for o in AssociatedDoubanOrder.all() if o.end_date.strftime('%Y-%m') >= query_month.strftime('%Y-%m') and o.contract_status in ECPM_CONTRACT_STATUS_LIST] orders = [{'jiafang_name': o.jiafang_name, 'client_name': o.client.name, 'campaign': o.campaign, 'start': o.start_date, 'end': o.end_date, 'money': o.money} for o in query_orders] # 全部直签豆瓣订单 else: query_orders = [o for o in DoubanOrder.all() if o.client_end.strftime('%Y-%m') >= query_month.strftime('%Y-%m') and o.contract_status in ECPM_CONTRACT_STATUS_LIST] orders = [{'agent_name': o.agent.name, 'client_name': o.client.name, 'campaign': o.campaign, 'start': o.client_start, 'end': o.client_end, 'money': o.money} for o in query_orders] th_count = 0 th_obj = [] for order in orders: if order['money']: pre_money = float(order['money']) / \ ((order['end'] - order['start']).days + 1) else: pre_money = 0 monthes_pre_days = get_monthes_pre_days(query_month, datetime.datetime.fromordinal(order['start'].toordinal()), datetime.datetime.fromordinal(order['end'].toordinal())) order['order_pre_money'] = [{'month': k['month'].strftime('%Y-%m'), 'money': '%.2f' % (pre_money * k['days'])} for k in monthes_pre_days] if len(monthes_pre_days) > th_count: th_obj = [ {'month': k['month'].strftime('%Y-%m')}for k in monthes_pre_days] th_count = len(monthes_pre_days) if 'excel' == request.args.get('extype', ''): if query_type == 1: filename = ( "%s-%s.xls" % (u"月度客户订单金额", datetime.datetime.now().strftime('%Y%m%d%H%M%S'))).encode('utf-8') elif query_type == 2: filename = ( "%s-%s.xls" % (u"月度媒体订单金额", datetime.datetime.now().strftime('%Y%m%d%H%M%S'))).encode('utf-8') elif query_type == 3: filename = ("%s-%s.xls" % (u"月度关联豆瓣订单金额", datetime.datetime.now().strftime('%Y%m%d%H%M%S'))).encode('utf-8') else: filename = ("%s-%s.xls" % (u"月度直签豆瓣订单金额", datetime.datetime.now().strftime('%Y%m%d%H%M%S'))).encode('utf-8') xls = write_excel(orders, query_type, th_obj) response = get_download_response(xls, filename) return response return tpl('/data_query/order/index.html', orders=orders, page=page, query_type=query_type, query_month=query_month.strftime('%Y-%m'), th_obj=th_obj)
def get(self): tOrder = Order() tUnattachedCustomer = Customer() tMasterCustomer = CustomerMaster() tMasterCustomer.masterIsPaBlacklisted = False tMasterCustomer.masterIsGlobalBlacklisted = False #Lists of customer masters tMasterCustomerEmailList = [] tMasterCustomerIpList = [] tMasterCustomerPhoneList = [] tMasterCustomerRsnList = [] tMasterCustomerPaypalList = [] tMasterCustomerEmailQuery = CustomerMaster.all() tMasterCustomerIpQuery = CustomerMaster.all() tMasterCustomerPhoneQuery = CustomerMaster.all() tMasterCustomerRsnQuery = CustomerMaster.all() tMasterCustomerPaypalQuery = CustomerMaster.all() #Final lists for deletion tDeletionList = [] #First get an unmastered customer tUnattachedCustomerQuery = Customer.all() tUnattachedCustomerQuery.filter("customerMaster", "") #tUnattachedCustomerQuery.filter("customerEmail", "*****@*****.**") tUnattachedCustomerList = tUnattachedCustomerQuery.fetch(1) if (len(tUnattachedCustomerList) > 0): tUnattachedCustomer = tUnattachedCustomerList[0] else: return #logging.debug("Testing with customer: " + str(tUnattachedCustomer.customerEmail)) #Defaults tEmail = "" tPhone = "" tIpList = [] #Assign from unmastered customer tEmail = str(tUnattachedCustomer.customerEmail).strip().lower() tPhone = str(tUnattachedCustomer.customerPhone).strip().lower() tPhone = re.sub(r'\D', '', tPhone) for tIp in tUnattachedCustomer.customerIpAddresses: tIp = str(tIp).strip() if (tIp != '' and tIp != None): tIpList.append(tIp) #Get Customer's Orders tOrderQuery = Order.all() tOrderQuery.filter("orderPaypalEmail", tEmail) tOrderList = tOrderQuery.fetch(200) #Merge together a list of the RSNs and Order Paypal IDs tRsnList = [] tPaypalList = [] for tOrder in tOrderList: if (tOrder.orderAccountName != None and tOrder.orderAccountName != ""): tTempRsn = str(tOrder.orderAccountName).lower().strip() tTempRsn = tTempRsn.replace(' ', '_') tTempRsn = tTempRsn.replace('-', '_') tRsnList.append(tTempRsn) if (tOrder.orderCustomerPaypalId != None and tOrder.orderCustomerPaypalId != ""): tPaypalList.append(str(tOrder.orderCustomerPaypalId)) #Dedupification tIpList = list(set(tIpList)) tRsnList = list(set(tRsnList)) tPaypalList = list(set(tPaypalList)) #Now that the data to search is filled we can start searching for masters if (tEmail != None and tEmail != ""): #logging.debug("Searching for masters with customer email: " + str(tEmail)) tMasterCustomerEmailQuery.filter("masterEmailList", tEmail) tMasterCustomerEmailList = tMasterCustomerEmailQuery.fetch(200) if (tPhone != None and tPhone != ""): #logging.debug("Searching for masters with customer phone: " + str(tPhone)) tMasterCustomerPhoneQuery.filter("masterPhoneList", tPhone) tMasterCustomerPhoneList = tMasterCustomerPhoneQuery.fetch(200) if (len(tIpList) > 0): for tIp in tIpList: if (tIp != None and tIp != ""): #logging.debug("Searching for masters with customer ip: " + str(tIp)) tMasterCustomerIpQuery = CustomerMaster.all() tMasterCustomerIpQuery.filter("masterIpList", tIp) tMasterCustomerIpList += tMasterCustomerIpQuery.fetch(200) if (len(tRsnList) > 0): for tRsn in tRsnList: if (tRsn != None and tRsn != ""): #logging.debug("Searching for masters with customer rsn: " + str(tRsn)) tMasterCustomerRsnQuery = CustomerMaster.all() tMasterCustomerRsnQuery.filter("masterRsnList", tRsn) tMasterCustomerRsnList += tMasterCustomerRsnQuery.fetch( 200) if (len(tPaypalList) > 0): for tPaypal in tPaypalList: if (tPaypal != None and tPaypal != ""): #logging.debug("Searching for masters with customer paypal id: " + str(tPaypal)) tMasterCustomerPaypalQuery = CustomerMaster.all() tMasterCustomerPaypalQuery.filter("masterPaypalIdList", tPaypal) tMasterCustomerPaypalList += tMasterCustomerPaypalQuery.fetch( 200) #logging.debug("Paypal Ids "+ str(tPaypalList)) #logging.debug("") #Merge the lists together tMasterCustomerList = [] tMasterCustomerList = tMasterCustomerEmailList + tMasterCustomerIpList + tMasterCustomerPaypalList + tMasterCustomerPhoneList + tMasterCustomerRsnList #if(len(tMasterCustomerEmailList) > 0): ##logging.debug("Master customer email list: " + str(tMasterCustomerEmailList)) #tMasterCustomerList += tMasterCustomerEmailList #if(len(tMasterCustomerPhoneList) > 0): ##logging.debug("Master customer phone list: " + str(tMasterCustomerPhoneList)) #tMasterCustomerList += tMasterCustomerPhoneList #if(len(tMasterCustomerIpList) > 0): ##logging.debug("Master customer ip list: " + str(tMasterCustomerIpList)) #tMasterCustomerList += tMasterCustomerIpList #if(len(tMasterCustomerRsnList) > 0): ##logging.debug("Master customer rsn list: " + str(tMasterCustomerRsnList)) #tMasterCustomerList += tMasterCustomerRsnList #if(len(tMasterCustomerPaypalList) > 0): ##logging.debug("Master customer paypalid list: " + str(tMasterCustomerPaypalList)) #tMasterCustomerList += tMasterCustomerPaypalList #logging.debug("Number of Master Customers: " + str(len(tMasterCustomerList))) #ttMC = CustomerMaster() #for ttMC in tMasterCustomerList: #logging.debug("Master customer list item key: " + str(ttMC.key())) #logging.debug(str(tMasterCustomerList)) #Assign or append lists of master customers if (len(tMasterCustomerList) > 1): tMC = CustomerMaster() tMcEmailList = [] tMcPhoneList = [] tMcIpList = [] tMcRsnList = [] tMcPaypalList = [] tMcCustomerList = [] for tMC in tMasterCustomerList: tMcEmailList += tMC.masterEmailList tMcPhoneList += tMC.masterPhoneList tMcIpList += tMC.masterIpList tMcRsnList += tMC.masterRsnList tMcPaypalList += tMC.masterPaypalIdList tMcCustomerList += tMC.masterCustomerList tDeletionList += [tMC] #for tMC in tMasterCustomerList: #if(len(tMC.masterEmailList) > 0): #tMcEmailList += tMC.masterEmailList ##tMcEmailList += tMasterCustomer.masterEmailList #if(len(tMC.masterPhoneList) > 0): #tMcPhoneList += tMC.masterPhoneList ##tMcPhoneList += tMasterCustomer.masterPhoneList #if(len(tMC.masterIpList) > 0): #tMcIpList += tMC.masterIpList ##tMcIpList += tMasterCustomer.masterIpList #if(len(tMC.masterRsnList) > 0): #tMcRsnList += tMC.masterRsnList ##tMcRsnList += tMasterCustomer.masterRsnList #if(len(tMC.masterPaypalIdList) > 0): #tMcPaypalList += tMC.masterPaypalIdList ##tMcPaypalList += tMasterCustomer.masterPaypalIdList #if(len(tMC.masterCustomerList) > 0): #tMcCustomerList += tMC.masterCustomerList ##tMcCustomerList += tMasterCustomer.masterCustomerList #tDeletionList += [tMC] tMcEmailList += [tEmail] tMcPhoneList += [tPhone] tMcIpList += tIpList tMcPaypalList += tPaypalList tMcRsnList += tRsnList tMcCustomerList += [str(tUnattachedCustomer.key())] tMasterCustomer.masterEmailList += list( set([str(x) for x in tMcEmailList if x != '' and x != None])) tMasterCustomer.masterPhoneList += list( set([str(x) for x in tMcPhoneList if x != '' and x != None])) tMasterCustomer.masterIpList += list( set([ str(x).strip() for x in tMcIpList if x != '' and x != None ])) tMasterCustomer.masterRsnList += list( set([ str(x).strip().lower().replace('-', '_').replace(' ', '_') for x in tMcRsnList if x != '' and x != None ])) tMasterCustomer.masterPaypalIdList += list( set([str(x) for x in tMcPaypalList if x != '' and x != None])) tMasterCustomer.masterCustomerList += list( set([str(x) for x in tMcCustomerList if x != '' and x != None])) ############################################################################################################################################## elif (len(tMasterCustomerList) == 1): tMC = tMasterCustomerList[0] #if(len(tMC.masterEmailList) > 0): #tMasterCustomer.masterEmailList += list(set([x for x in tMC.masterEmailList if x != '' and x != None])) #if(len(tMC.masterPhoneList) > 0): #tMasterCustomer.masterPhoneList += list(set([x for x in tMC.masterPhoneList if x != '' and x != None])) #if(len(tMC.masterIpList) > 0): #tMasterCustomer.masterIpList += list(set([x for x in tMC.masterIpList if x != '' and x != None])) #if(len(tMC.masterRsnList) > 0): #tMasterCustomer.masterRsnList += list(set([str(x).strip().lower().replace('-','_').replace(' ','_') for x in tMC.masterRsnList if x != '' and x != None])) #if(len(tMC.masterPaypalIdList) > 0): #tMasterCustomer.masterPaypalIdList += list(set([x for x in tMC.masterPaypalIdList if x != '' and x != None])) tMC.masterEmailList += [tEmail] tMC.masterIpList += tIpList tMC.masterPaypalIdList += tPaypalList tMC.masterPhoneList += [tPhone] tMC.masterRsnList += tRsnList tMasterCustomer.masterEmailList += list( set([x for x in tMC.masterEmailList if x != '' and x != None])) tMasterCustomer.masterPhoneList += list( set([x for x in tMC.masterPhoneList if x != '' and x != None])) tMasterCustomer.masterIpList += list( set([x for x in tMC.masterIpList if x != '' and x != None])) tMasterCustomer.masterRsnList += list( set([ str(x).strip().lower().replace('-', '_').replace(' ', '_') for x in tMC.masterRsnList if x != '' and x != None ])) tMasterCustomer.masterPaypalIdList += list( set([ x for x in tMC.masterPaypalIdList if x != '' and x != None ])) tMasterCustomer.masterCustomerList += [ str(tUnattachedCustomer.key()) ] tDeletionList = [tMC] ############################################################################################################################################## elif (len(tMasterCustomerList) == 0): if (tMasterCustomer.masterCustomerList == None or len(tMasterCustomer.masterCustomerList) == 0): tTempList = [] try: tTempList.append(str(tUnattachedCustomer.key())) except: tUnattachedCustomer.put() tTempList.append(str(tUnattachedCustomer.key())) tMasterCustomer.masterCustomerList += tTempList if (tMasterCustomer.masterEmailList == None or len(tMasterCustomer.masterEmailList) == 0): tTempList = [] tTempList.append(str(tUnattachedCustomer.customerEmail)) tMasterCustomer.masterEmailList += tTempList if (tMasterCustomer.masterIpList == None or len(tMasterCustomer.masterIpList) == 0): tTempList = [] tTempList += list(set(tUnattachedCustomer.customerIpAddresses)) tMasterCustomer.masterIpList += tTempList if (tMasterCustomer.masterPaypalIdList == None or len(tMasterCustomer.masterPaypalIdList) == 0): tTempList = [] tTempList.append(str(tUnattachedCustomer.customerPaypalId)) tMasterCustomer.masterPaypalIdList += tTempList if (tMasterCustomer.masterPhoneList == None or len(tMasterCustomer.masterPhoneList) == 0): tTempList = [] tTempList.append(str(tUnattachedCustomer.customerPhone)) tMasterCustomer.masterPhoneList += tTempList if (tMasterCustomer.masterRsnList == None or len(tMasterCustomer.masterRsnList) == 0): tTempList = [] tTempList += list(set(tRsnList)) tMasterCustomer.masterRsnList += tTempList if (tUnattachedCustomer.customerIsPaBlacklisted == True): tMasterCustomer.masterIsPaBlacklisted = True if (tUnattachedCustomer.customerIsGlobalBlacklisted == True): tMasterCustomer.masterIsGlobalBlacklisted = True #for tProperty, tValue in tUnattachedCustomer.__dict__.iteritems(): #logging.debug("Customer property " + str(tProperty) + " with value " + str(tValue)) #for tProperty, tValue in tMasterCustomer.__dict__.iteritems(): #logging.debug("Master property " + str(tProperty) + " with value " + str(tValue)) tMaster = CustomerMaster() if (len(tDeletionList) > 0): for tMaster in tDeletionList: tMaster.delete() tMasterKey = tMasterCustomer.put() #update other customers if there's >1 tUnattachedCustomer.customerMaster = str(tMasterKey) tUnattachedCustomer.put() tCustomer = Customer() for tCustomerKey in tMasterCustomer.masterCustomerList: tCustomer = Customer.get(tCustomerKey) tCustomer.customerMaster = str(tMasterKey) tCustomer.put()
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
def index(): if not (g.user.is_super_leader() or g.user.is_aduit() or g.user.is_finance() or g.user.is_contract()): abort(403) shenji = int(request.values.get('shenji', 0)) now_date = datetime.datetime.now() year = int(request.values.get('year', now_date.year)) # 获取整年月份 pre_year_month = get_monthes_pre_days(datetime.datetime.strptime(str(year) + '-01', '%Y-%m'), datetime.datetime.strptime(str(year) + '-12', '%Y-%m')) # 获取所有回款包含返点发票 back_money_data = _all_douban_order_back_moneys() client_back_money_data = _all_client_order_back_moneys() # 获取代理返点系数 all_agent_rebate = _all_agent_rebate() # 获取所有外包 all_outsource_data = _all_douban_order_outsource() # 获取当年豆瓣合同 orders = DoubanOrder.query.filter(DoubanOrder.status == 1, DoubanOrder.contract != '') # 去重合同 orders = [k for k in orders if k.client_start.year == year or k.client_end.year == year] # 格式化合同 orders = [_douban_order_to_dict(k, back_money_data, all_agent_rebate, pre_year_month, all_outsource_data, shenji) for k in orders] # 获取豆瓣合同结束 orders = [k for k in orders if k['contract_status'] in [2, 4, 5, 10, 19, 20]] # 获取关联豆瓣合同 medium_orders = [_medium_order_to_dict(k, client_back_money_data, all_agent_rebate, pre_year_month, all_outsource_data, shenji) for k in Order.all() if (k.medium_start.year == year or k.medium_end.year == year) and k.associated_douban_order] orders += [k for k in medium_orders if k['contract_status'] in [2, 4, 5, 10, 19, 20] and k['status'] == 1] # 获取关联豆瓣合同结束 orders = sorted( orders, key=operator.itemgetter('start_date_cn'), reverse=False) total_outsource_data = [0 for k in range(12)] total_money_data = [0 for k in range(12)] total_money_rebate_data = [0 for k in range(12)] total_profit_data = [0 for k in range(12)] for k in orders: total_money_data = numpy.array( total_money_data) + numpy.array(k['money_data']) total_outsource_data = numpy.array( total_outsource_data) + numpy.array(k['outsource_data']) total_money_rebate_data = numpy.array( total_money_rebate_data) + numpy.array(k['money_rebate_data']) total_profit_data = numpy.array( total_profit_data) + numpy.array(k['profit_data']) if request.values.get('action') == 'excel': return write_douban_order_excel(orders=orders, year=year, total_money_data=total_money_data, total_money_rebate_data=total_money_rebate_data, total_profit_data=total_profit_data, total_outsource_data=total_outsource_data, shenji=shenji) if shenji: tpl_html = '/shenji/cost_income_douban_order_s.html' else: tpl_html = '/shenji/cost_income_douban_order.html' return tpl(tpl_html, orders=orders, year=year, total_money_data=total_money_data, total_money_rebate_data=total_money_rebate_data, total_outsource_data=total_outsource_data, total_profit_data=total_profit_data)
def get_Orders(self): # This is not at the top to prevent circular imports. from models.order import Order return Order.all().ancestor(self)
def GetContext(self): tUser = self.GetUser() tCustomerList = [] tCustomerOrders = [] tCustomerOrderKeys = [] tOrderData = {} tOrder = Order() tShowSearch = False tCustomerLookup = CustomerHandler() tCustomerKey = urllib.unquote(self.request.get('key')) if (tCustomerKey): tCustomerList.append( tCustomerLookup.GetCustomerByKey(tCustomerKey)) #logging.debug(str(len(tCustomerList))) if (tCustomerList == None or len(tCustomerList) == 0): tShowSearch = True else: tShowSearch = False tCustomer = Customer() tCustomer = tCustomerList[0] #Get date 30 days ago tStartDate = datetime.datetime.now() tIncrement = datetime.timedelta(days=-30) tEndDate = tStartDate + tIncrement tCustomerOrderQuery = Order.all() tCustomerOrderQuery.filter("orderCreated >", tEndDate) tCustomerOrderQuery.filter("orderCustomer", tCustomerKey) 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 = datetime.datetime.now() tIncrement = datetime.timedelta(days=-1) tEndDate = tStartDate + tIncrement tCustomerOrderQuery = Order.all().filter("orderCreated >", tEndDate) tCustomerOrderQuery.filter("orderCustomer", tCustomerKey) 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 = datetime.datetime.now() #tIncrement = datetime.timedelta(days = -15) #tEndDate = tStartDate + tIncrement #tCustomerOrderQuery = Order.all().filter("orderCreated >", tEndDate) #tCustomerOrderQuery.filter("orderCustomer", tCustomerKey) #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) #logging.debug(str(tCustomerKey)) tOrderQuery = Order.all() tOrderQuery.filter("orderCustomer", tCustomerKey) tOrderQuery.order("-orderCreated") tCustomerOrders = tOrderQuery.fetch(20) #logging.debug(str(tCustomerOrders)) tShowSearch = str(tShowSearch) return { 'result': tCustomerList, 'customerorders': tCustomerOrders, 'tOrderData': tOrderData, 'search': tShowSearch, }
def index(): if not (g.user.is_super_leader() or g.user.is_media_leader()): return abort(403) now_date = datetime.datetime.now() year = int(request.values.get('year', now_date.year)) start_date_month = datetime.datetime.strptime( str(year) + '-01' + '-01', '%Y-%m-%d') end_date_month = datetime.datetime.strptime( str(year) + '-12' + '-31', '%Y-%m-%d') pre_monthes = get_monthes_pre_days(start_date_month, end_date_month) medium_id = int(request.values.get('medium_id', 0)) ex_medium_orders = [o for o in Order.all( ) if o.medium_start.year == year or o.medium_end.year == year] obj_data = [] for order in ex_medium_orders: pre_month_sale_money = pre_month_money(order.sale_money, order.medium_start, order.medium_end) pre_month_medium_money2 = pre_month_money(order.medium_money2, order.medium_start, order.medium_end) # 单笔返点 agent_rebate = order.client_order.agent_rebate try: self_agent_rebate = order.client_order.self_agent_rebate self_agent_rebate = float(self_agent_rebate.split('-')[0]) self_agent_rebate_value = float(self_agent_rebate.split('-')[1]) except: self_agent_rebate = 0 self_agent_rebate_value = 0 for p in range(len(pre_month_sale_money)): d_order = {} d_order['medium_id'] = order.medium.id d_order['money'] = order.client_order.money d_order['contract_status'] = order.client_order.contract_status d_order['status'] = order.client_order.status d_order['sale_money'] = pre_month_sale_money[p]['money'] d_order['medium_money2'] = pre_month_medium_money2[p]['money'] d_order['month_day'] = pre_month_sale_money[p]['month_day'] medium_rebate = order.medium_rebate_by_year(d_order['month_day']) # 媒体单笔返点 try: self_medium_rebate_data = order.self_medium_rebate self_medium_rebate = self_medium_rebate_data.split('-')[0] self_medium_rebate_value = float(self_medium_rebate_data.split('-')[1]) except: self_medium_rebate = 0 self_medium_rebate_value = 0 if int(self_medium_rebate): if d_order['sale_money']: d_order['medium_rebate_value'] = d_order['sale_money'] / d_order['money'] * self_medium_rebate_value else: d_order['medium_rebate_value'] == 0 else: d_order['medium_rebate_value'] = d_order['medium_money2'] * medium_rebate / 100 if self_agent_rebate: if d_order['money']: d_order['agent_rebate_value'] = self_agent_rebate_value * d_order['sale_money'] / d_order['money'] else: d_order['agent_rebate_value'] = 0 else: d_order['agent_rebate_value'] = d_order['sale_money'] * agent_rebate / 100 obj_data.append(d_order) ex_medium_orders = [k for k in obj_data if k[ 'contract_status'] not in [0, 1, 3, 6, 7, 8, 81, 9] and k['status'] == 1] medium_data = [] if medium_id: mediums = Medium.query.filter_by(id=medium_id) else: mediums = Medium.all() sum_sale_money = 0 for k in mediums: sale_money_data = [] medium_money2_data = [] medium_rebate_data = [] agent_rebate_data = [] for i in pre_monthes: sale_money_data.append(sum([ex['sale_money'] for ex in ex_medium_orders if ex[ 'medium_id'] == k.id and ex['month_day'].date() == i['month'].date()])) medium_money2_data.append(sum([ex['medium_money2'] for ex in ex_medium_orders if ex[ 'medium_id'] == k.id and ex['month_day'].date() == i['month'].date()])) medium_rebate_data.append(sum([ex['medium_rebate_value'] for ex in ex_medium_orders if ex[ 'medium_id'] == k.id and ex['month_day'].date() == i['month'].date()])) agent_rebate_data.append(sum([ex['agent_rebate_value'] for ex in ex_medium_orders if ex[ 'medium_id'] == k.id and ex['month_day'].date() == i['month'].date()])) sum_sale_money += sum(sale_money_data) medium_data.append({'id': k.id, 'name': k.name, 'level': k.level or 100, 'sale_money_data': sale_money_data, 'medium_money2_data': medium_money2_data, 'medium_rebate_data': medium_rebate_data, 'agent_rebate_data': agent_rebate_data}) print sum_sale_money medium_data = sorted( medium_data, key=operator.itemgetter('level'), reverse=False) if request.values.get('action', '') == 'download': return write_client_excel(medium_data, year) return tpl('/data_query/medium/index.html', medium_data=medium_data, medium_id=medium_id, year=year, params="?medium_id=%s&year=%s" % ( medium_id, str(year)), s_mediums=Medium.all())
def clear_order_items(): os = Order.all() for o in os: o.items = [] o.save() return redirect(url_for('admin.product_list'))
def clear_orders(): os = Order.all() for o in os: o.delete() return redirect(url_for('admin.product_list'))
def index(): if not (g.user.is_super_leader() or g.user.is_aduit() or g.user.is_finance()): abort(403) location = int(request.values.get('location', 1)) now_date = datetime.datetime.now() year = int(request.values.get('year', now_date.year)) # 获取所有关联豆瓣订单,用于判断媒体订单是否是关联豆瓣订单,全部取出减少链接数据库时间 ass_douban_order_ids = [ k.medium_order_id for k in AssociatedDoubanOrder.all() ] orders = [ _format_douban_order(k, year) for k in DoubanOrder.all() if k.client_start.year >= year - 2 and k.client_start.year <= year ] orders += [ _format_client_order(k, year, ass_douban_order_ids) for k in Order.all() if k.medium_start.year >= year - 2 and k.medium_start.year <= year ] # 去掉撤单、申请中的合同 orders = [ k for k in orders if k['contract_status'] in [2, 4, 5, 10, 19, 20] and k['status'] == 1 and k['contract'] ] if location == 1: money, data = _fix_client_data(HB_data, orders, location) elif location == 2: money, data = _fix_client_data(HD_data, orders, location) elif location == 3: money, data = _fix_client_data(HN_data, orders, location) action = request.values.get('action', '') if action == 'excel': return write_client_total_excel(year=year, data=data, money=money, location=location) # 组装数据用于画图 categories_1 = [] series_1 = [{ 'name': str(year - 2) + u'年新媒体', 'data': [], 'stack': str(year - 2) }, { 'name': str(year - 2) + u'年豆瓣', 'data': [], 'stack': str(year - 2) }, { 'name': str(year - 1) + u'年新媒体', 'data': [], 'stack': str(year - 1) }, { 'name': str(year - 1) + u'年豆瓣', 'data': [], 'stack': str(year - 1) }, { 'name': str(year) + u'年新媒体', 'data': [], 'stack': str(year) }, { 'name': str(year) + u'年豆瓣', 'data': [], 'stack': str(year) }] categories_2 = [] series_2 = [{ 'name': str(year - 2) + u'年新媒体', 'data': [], 'stack': str(year - 2) }, { 'name': str(year - 2) + u'年豆瓣', 'data': [], 'stack': str(year - 2) }, { 'name': str(year - 1) + u'年新媒体', 'data': [], 'stack': str(year - 1) }, { 'name': str(year - 1) + u'年豆瓣', 'data': [], 'stack': str(year - 1) }, { 'name': str(year) + u'年新媒体', 'data': [], 'stack': str(year) }, { 'name': str(year) + u'年豆瓣', 'data': [], 'stack': str(year) }] for k in data: clients = k['clients'] for c in range(len(clients)): if c <= len(clients) / 2: categories_1.append(clients[c]['name']) series_1[0]['data'].append(clients[c]['client_money'][0]) series_1[1]['data'].append(clients[c]['client_money'][1]) series_1[2]['data'].append(clients[c]['client_money'][3]) series_1[3]['data'].append(clients[c]['client_money'][4]) series_1[4]['data'].append(clients[c]['client_money'][7] + clients[c]['client_money'][9] + clients[c]['client_money'][11] + clients[c]['client_money'][13]) series_1[5]['data'].append(clients[c]['client_money'][8] + clients[c]['client_money'][10] + clients[c]['client_money'][12] + clients[c]['client_money'][14]) else: categories_2.append(clients[c]['name']) series_2[0]['data'].append(clients[c]['client_money'][0]) series_2[1]['data'].append(clients[c]['client_money'][1]) series_2[2]['data'].append(clients[c]['client_money'][3]) series_2[3]['data'].append(clients[c]['client_money'][4]) series_2[4]['data'].append(clients[c]['client_money'][7] + clients[c]['client_money'][9] + clients[c]['client_money'][11] + clients[c]['client_money'][13]) series_2[5]['data'].append(clients[c]['client_money'][8] + clients[c]['client_money'][10] + clients[c]['client_money'][12] + clients[c]['client_money'][14]) return tpl('/data_query/super_leader/client_total.html', year=year, data=data, money=money, location=location, categories_1=json.dumps(categories_1), series_1=json.dumps(series_1), categories_2=json.dumps(categories_2), series_2=json.dumps(series_2))
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 ProcessOrder(self, pArgumentDic): tOrderHandler = OrderHandler() tCustomerHandler = CustomerHandler() tCustomer = Customer() tPaypalOrder = PaypalOrder() tArgumentDic = pArgumentDic #Assign Values from POST from Paypal IPN tTransactionId = tArgumentDic['txn_id'] tAlphaMatch = re.compile('[^A-Za-z0-9]+') tAlphaSpaceMatch = re.compile('[^A-Za-z0-9 ]+') #Short circuits the order process for special PA page if ('payer_email' in tArgumentDic.keys()): if (tArgumentDic['payer_email'] == '*****@*****.**'): tPaypalOrder.ProcessPlayerAuctions(tArgumentDic) return try: tGoldAmount = tArgumentDic['option_name7'] except: tGoldAmount = "" try: tCustomerFirstName = tAlphaSpaceMatch.sub( '', tArgumentDic['first_name']) except: tCustomerFirstName = "" try: tCustomerLastName = tAlphaSpaceMatch.sub('', tArgumentDic['last_name']) except: tCustomerLastName = "" try: tCustomerName = tAlphaSpaceMatch.sub('', tArgumentDic['option_name1']) except: tCustomerName = "" try: tEmail = tArgumentDic['option_name2'] except: tEmail = "" tPaypalEmail = str(tArgumentDic['payer_email']).lower() try: tMobilePhone = tArgumentDic['option_name3'] tMobilePhone = re.sub(r'\D', '', tMobilePhone) except: tMobilePhone = "" try: tRsName = tArgumentDic['option_name4'].strip().lower() tRsName = tRsName.replace(' ', '_') tRsName = tRsName.replace('-', '_') except: tRsName = "" try: tCombatLevel = "" except: tCombatLevel = "" #try: #tReferCode = str(tArgumentDic['option_name5']).strip() #except: tReferCode = "" try: tPromotionCode = str(tArgumentDic['option_name5']).strip() except: tPromotionCode = "" tOrderIp = tArgumentDic['custom'] tMembers = "" try: tOrderQuery = Order.all().filter('orderTransactionId', tTransactionId) tOrder = tOrderQuery.fetch(1)[0] except: tOrder = Order() if ('fake' in tArgumentDic.keys()): #logging.debug('Fake key hit') #logging.debug(str(tArgumentDic['fake'])) if (tArgumentDic['fake'] == 'True'): tOrder.orderIsGenerated = True tOrder.orderFormName = tCustomerName tOrder.orderCombatLevel = tCombatLevel if (len(tGoldAmount) == 0): tUrl = "https://api-3t.paypal.com/nvp" #tOperation = "AddressVerify" tOperation = "GetTransactionDetails" #Get Paypal Information #tPaypal = PaypalTrigger() tResultDictionary = {} tPaypalPayload = {} tPayload = {} tPaypalPayload['METHOD'] = tOperation tPaypalPayload['TRANSACTIONID'] = tTransactionId tPayloadEncoded = tOrderHandler.GeneratePayload(tPaypalPayload) request_cookies = mechanize.CookieJar() request_opener = mechanize.build_opener( mechanize.HTTPCookieProcessor(request_cookies)) request_opener.addheaders = [('Content-Type', 'application/x-www-form-urlencoded')] mechanize.install_opener(request_opener) tResponse = mechanize.urlopen(url=tUrl, timeout=25.0, data=tPayloadEncoded) tResult = str(urllib.unquote(tResponse.read())) tResultSplit = tResult.split('&') for tPair in tResultSplit: tSplitPair = tPair.split("=") if (len(tSplitPair) == 1): tSplitPair.append("") tResultDictionary[tSplitPair[0]] = tSplitPair[1] logging.debug(tSplitPair[0] + " " + tSplitPair[1]) tGoldAmountString = tResultDictionary['L_NAME0'] logging.debug("Gold amount string %s".format(tGoldAmountString)) try: tGoldRegex = re.compile("([0-9]*?[m|M]).T") tGoldMatch = tGoldRegex.findall(tGoldAmountString) #logging.debug("Backup gold amount parser hit, string " + tGoldAmountString + " Match: " + tGoldMatch[0]) tGoldAmount = tGoldMatch[0] except: tGoldRegex = re.compile("([0-9]*?[m|M]).T") tGoldMatch = tGoldRegex.findall(tGoldAmountString) try: #logging.debug("Backup gold amount parser hit, string " + tGoldAmountString + " Match: " + tGoldMatch[0]) tGoldAmount = tGoldMatch[0] except: #logging.debug("No gold match") tGoldAmount = "" tOrder.orderQuantity = NumberToGp.ConvertBetToInt(tGoldAmount) tOrder.orderSimpleGoldAmount = tGoldAmount tOrder.orderFormEmail = tEmail tOrder.orderAccountName = tRsName tOrder.orderMobileNumber = tMobilePhone tOrder.orderPromotionalCode = tPromotionCode.lower() tOrder.orderIp = tOrderIp if (tMembers == "yes"): tOrder.orderCustomerIsMember = True else: tOrder.orderCustomerIsMember = False #Paypal Info tOrder.orderTransactionId = tTransactionId tOrder.orderPaypalFirstName = tCustomerFirstName tOrder.orderPaypalLastName = tCustomerLastName tOrder.orderCost = float(tArgumentDic['payment_gross']) tOrder.orderCustomerPaypalId = tArgumentDic['payer_id'] tOrder.orderPaypalEmail = str(tPaypalEmail).lower() tAssignedAgentNick = tPaypalOrder.GetAssignedAgent(tOrder) tOrder.orderAssignedAgent = tAssignedAgentNick #logging.debug("Order assigned to agent: " + str(tAssignedAgentNick)) tOrder.orderReferralCode = tReferCode tOrder.orderDeliver = 'False' if (tOrder.orderVerificationCode == None or tOrder.orderVerificationCode == ''): tOrder.orderVerificationCode = re.sub(r'\W', '', str(uuid.uuid4())).lower() tCurrentEocPrices = PriceContainer.GetCurrentPriceDic() tCurrent07Prices = PriceContainer.GetCurrentPriceDic07() tSkip07 = False if tOrder.orderSimpleGoldAmount in tCurrentEocPrices.keys(): if str(tOrder.orderCost) == str( tCurrentEocPrices[tOrder.orderSimpleGoldAmount]): tOrder.orderGoldType = 'eoc' tSkip07 = True if not tSkip07: if tOrder.orderSimpleGoldAmount in tCurrent07Prices.keys(): if str(tOrder.orderCost) == str( tCurrent07Prices[tOrder.orderSimpleGoldAmount]): tOrder.orderGoldType = '07' tOrderKey = str(tOrder.put()) #logging.debug("Order Saved: " + str(tOrderKey)) taskqueue.add(url="/iplookup", countdown=1, params={ "ip": tOrderIp, "transid": tTransactionId }) tUsedBonus = [] tCustomerList = tCustomerHandler.GetCustomerByPpid( tOrder.orderCustomerPaypalId) if (len(tCustomerList) == 1): tCustomer = tCustomerList[0] tIpList = tCustomer.customerIpAddresses tIpList.append(tOrderIp) tCustomer.customerIpAddresses = tIpList tOrderList = tCustomer.customerOrders tOrderList.append(tOrderKey) tCustomer.customerOrders = tOrderList tCustomer.customerOrderCount = int( tCustomer.customerOrderCount) + 1 #tUsedBonus = tCustomer.customerUsedBonus tUsedBonus = Order.GetCustomerPromoCodes( tCustomer.customerPaypalId) #tOrder.orderCustomer = str(tCustomer.key()) elif (len(tCustomerList) == 0): tCustomer.customerEmail = str(tOrder.orderPaypalEmail).lower() tCustomer.customerName = tCustomerName tCustomer.customerFirstName = tOrder.orderPaypalFirstName tCustomer.customerLastName = tOrder.orderPaypalLastName tCustomer.customerIpAddresses = [tOrderIp] tCustomer.customerOrders = [tOrderKey] tCustomer.customerOrderCount = 1 tCustomer.customerPhone = tMobilePhone tCustomer.customerEmailVerified = False tCustomer.customerPhoneVerified = False tCustomer.customerIdVerified = False tCustomer.customerPaypalId = tOrder.orderCustomerPaypalId tCustomer.customerIsGlobalBlacklisted = False tCustomer.customerIsPaBlacklisted = False tPromoCode = "" tPromoCode = tOrder.orderPromotionalCode #logging.debug("Order Promo Code: " + str(tOrder.orderPromotionalCode)) tPromo = Promo() tPromoCode = tPromoCode.lower() try: logging.debug("Promo Code: " + str(tPromoCode)) tPromo = Promo.GetPromoByCode(tPromoCode) logging.debug("Promo: " + str(tPromo)) tGoldAmount = tOrder.orderQuantity logging.debug("Gold Amount: " + str(tGoldAmount)) logging.debug("Promo is active: " + str(tPromo.promoIsActive)) if ((tPromo.promoIsActive) and (tPromo.promoUses <= tPromo.promoLimit)): if (tPromo.promoLimit != 0): tPromo.promoUses = tPromo.promoUses + 1 if ((tPromoCode in tUsedBonus) == True): tPercentBonus = 0.0 else: tPercentBonus = tGoldAmount * tPromo.promoPercentage #tUsedBonus.append(tPromoCode) tGoldAmount = tGoldAmount + tPercentBonus tGoldAmount = tGoldAmount + tPromo.promoGoldAmount tTotalBonusFloat = tPercentBonus + tPromo.promoGoldAmount logging.debug("Bonus float: " + str(tTotalBonusFloat)) tOrder.orderBonusQuantity = int(tTotalBonusFloat) logging.debug("Total Bonus Float " + str(tTotalBonusFloat)) logging.debug("Promo Gold Amount " + str(tPromo.promoGoldAmount)) logging.debug("Promo Percentage " + str(tPercentBonus)) except: tOrder.orderBonusQuantity = 0 #tCustomer.customerUsedBonus = tUsedBonus tCustomerKey = str(tCustomer.put()) tOrder.orderCustomer = tCustomerKey tOrderKey = str(tOrder.put()) if (tCustomerName == ""): tCustomerName = tCustomerFirstName + " " + tCustomerLastName if (tGoldAmount == None or len(str(tGoldAmount)) == 0): tGoldAmount = tGoldAmountString response = taskqueue.add(url="/emailnotify", countdown=1, params={ "email": tPaypalEmail, "gold": tGoldAmount, "name": tCustomerName, 'key': tOrderKey }) logging.debug(str(response))
def get(self): tOrder = Order() tUnattachedCustomer = Customer() tMasterCustomer = CustomerMaster() tMasterCustomer.masterIsPaBlacklisted = False tMasterCustomer.masterIsGlobalBlacklisted = False #Lists of customer masters tMasterCustomerEmailList = [] tMasterCustomerIpList = [] tMasterCustomerPhoneList = [] tMasterCustomerRsnList = [] tMasterCustomerPaypalList = [] tMasterCustomerEmailQuery = CustomerMaster.all() tMasterCustomerIpQuery = CustomerMaster.all() tMasterCustomerPhoneQuery = CustomerMaster.all() tMasterCustomerRsnQuery = CustomerMaster.all() tMasterCustomerPaypalQuery = CustomerMaster.all() #Final lists for deletion tDeletionList = [] #First get an unmastered customer tUnattachedCustomerQuery = Customer.all() tUnattachedCustomerQuery.filter("customerMaster", "") #tUnattachedCustomerQuery.filter("customerEmail", "*****@*****.**") tUnattachedCustomerList = tUnattachedCustomerQuery.fetch(1) if(len(tUnattachedCustomerList) > 0): tUnattachedCustomer = tUnattachedCustomerList[0] else: return #logging.debug("Testing with customer: " + str(tUnattachedCustomer.customerEmail)) #Defaults tEmail = "" tPhone = "" tIpList = [] #Assign from unmastered customer tEmail = str(tUnattachedCustomer.customerEmail).strip().lower() tPhone = str(tUnattachedCustomer.customerPhone).strip().lower() tPhone = re.sub(r'\D', '', tPhone) for tIp in tUnattachedCustomer.customerIpAddresses: tIp = str(tIp).strip() if (tIp != '' and tIp != None): tIpList.append(tIp) #Get Customer's Orders tOrderQuery = Order.all() tOrderQuery.filter("orderPaypalEmail", tEmail) tOrderList = tOrderQuery.fetch(200) #Merge together a list of the RSNs and Order Paypal IDs tRsnList = [] tPaypalList = [] for tOrder in tOrderList: if(tOrder.orderAccountName != None and tOrder.orderAccountName != ""): tTempRsn = str(tOrder.orderAccountName).lower().strip() tTempRsn = tTempRsn.replace(' ', '_') tTempRsn = tTempRsn.replace('-', '_') tRsnList.append(tTempRsn) if(tOrder.orderCustomerPaypalId != None and tOrder.orderCustomerPaypalId != ""): tPaypalList.append(str(tOrder.orderCustomerPaypalId)) #Dedupification tIpList = list(set(tIpList)) tRsnList = list(set(tRsnList)) tPaypalList = list(set(tPaypalList)) #Now that the data to search is filled we can start searching for masters if(tEmail != None and tEmail != ""): #logging.debug("Searching for masters with customer email: " + str(tEmail)) tMasterCustomerEmailQuery.filter("masterEmailList", tEmail) tMasterCustomerEmailList = tMasterCustomerEmailQuery.fetch(200) if(tPhone != None and tPhone != ""): #logging.debug("Searching for masters with customer phone: " + str(tPhone)) tMasterCustomerPhoneQuery.filter("masterPhoneList", tPhone) tMasterCustomerPhoneList = tMasterCustomerPhoneQuery.fetch(200) if(len(tIpList) > 0): for tIp in tIpList: if(tIp != None and tIp != ""): #logging.debug("Searching for masters with customer ip: " + str(tIp)) tMasterCustomerIpQuery = CustomerMaster.all() tMasterCustomerIpQuery.filter("masterIpList", tIp) tMasterCustomerIpList += tMasterCustomerIpQuery.fetch(200) if(len(tRsnList) > 0): for tRsn in tRsnList: if(tRsn != None and tRsn != ""): #logging.debug("Searching for masters with customer rsn: " + str(tRsn)) tMasterCustomerRsnQuery = CustomerMaster.all() tMasterCustomerRsnQuery.filter("masterRsnList", tRsn) tMasterCustomerRsnList += tMasterCustomerRsnQuery.fetch(200) if(len(tPaypalList) > 0): for tPaypal in tPaypalList: if(tPaypal != None and tPaypal != ""): #logging.debug("Searching for masters with customer paypal id: " + str(tPaypal)) tMasterCustomerPaypalQuery = CustomerMaster.all() tMasterCustomerPaypalQuery.filter("masterPaypalIdList", tPaypal) tMasterCustomerPaypalList += tMasterCustomerPaypalQuery.fetch(200) #logging.debug("Paypal Ids "+ str(tPaypalList)) #logging.debug("") #Merge the lists together tMasterCustomerList = [] tMasterCustomerList = tMasterCustomerEmailList + tMasterCustomerIpList + tMasterCustomerPaypalList + tMasterCustomerPhoneList + tMasterCustomerRsnList #if(len(tMasterCustomerEmailList) > 0): ##logging.debug("Master customer email list: " + str(tMasterCustomerEmailList)) #tMasterCustomerList += tMasterCustomerEmailList #if(len(tMasterCustomerPhoneList) > 0): ##logging.debug("Master customer phone list: " + str(tMasterCustomerPhoneList)) #tMasterCustomerList += tMasterCustomerPhoneList #if(len(tMasterCustomerIpList) > 0): ##logging.debug("Master customer ip list: " + str(tMasterCustomerIpList)) #tMasterCustomerList += tMasterCustomerIpList #if(len(tMasterCustomerRsnList) > 0): ##logging.debug("Master customer rsn list: " + str(tMasterCustomerRsnList)) #tMasterCustomerList += tMasterCustomerRsnList #if(len(tMasterCustomerPaypalList) > 0): ##logging.debug("Master customer paypalid list: " + str(tMasterCustomerPaypalList)) #tMasterCustomerList += tMasterCustomerPaypalList #logging.debug("Number of Master Customers: " + str(len(tMasterCustomerList))) #ttMC = CustomerMaster() #for ttMC in tMasterCustomerList: #logging.debug("Master customer list item key: " + str(ttMC.key())) #logging.debug(str(tMasterCustomerList)) #Assign or append lists of master customers if(len(tMasterCustomerList) > 1): tMC = CustomerMaster() tMcEmailList = [] tMcPhoneList = [] tMcIpList = [] tMcRsnList = [] tMcPaypalList = [] tMcCustomerList = [] for tMC in tMasterCustomerList: tMcEmailList += tMC.masterEmailList tMcPhoneList += tMC.masterPhoneList tMcIpList += tMC.masterIpList tMcRsnList += tMC.masterRsnList tMcPaypalList += tMC.masterPaypalIdList tMcCustomerList += tMC.masterCustomerList tDeletionList += [tMC] #for tMC in tMasterCustomerList: #if(len(tMC.masterEmailList) > 0): #tMcEmailList += tMC.masterEmailList ##tMcEmailList += tMasterCustomer.masterEmailList #if(len(tMC.masterPhoneList) > 0): #tMcPhoneList += tMC.masterPhoneList ##tMcPhoneList += tMasterCustomer.masterPhoneList #if(len(tMC.masterIpList) > 0): #tMcIpList += tMC.masterIpList ##tMcIpList += tMasterCustomer.masterIpList #if(len(tMC.masterRsnList) > 0): #tMcRsnList += tMC.masterRsnList ##tMcRsnList += tMasterCustomer.masterRsnList #if(len(tMC.masterPaypalIdList) > 0): #tMcPaypalList += tMC.masterPaypalIdList ##tMcPaypalList += tMasterCustomer.masterPaypalIdList #if(len(tMC.masterCustomerList) > 0): #tMcCustomerList += tMC.masterCustomerList ##tMcCustomerList += tMasterCustomer.masterCustomerList #tDeletionList += [tMC] tMcEmailList += [tEmail] tMcPhoneList += [tPhone] tMcIpList += tIpList tMcPaypalList += tPaypalList tMcRsnList += tRsnList tMcCustomerList += [str(tUnattachedCustomer.key())] tMasterCustomer.masterEmailList += list(set([str(x) for x in tMcEmailList if x != '' and x != None])) tMasterCustomer.masterPhoneList += list(set([str(x) for x in tMcPhoneList if x != '' and x != None])) tMasterCustomer.masterIpList += list(set([str(x).strip() for x in tMcIpList if x != '' and x != None])) tMasterCustomer.masterRsnList += list(set([str(x).strip().lower().replace('-','_').replace(' ','_') for x in tMcRsnList if x != '' and x != None])) tMasterCustomer.masterPaypalIdList += list(set([str(x) for x in tMcPaypalList if x != '' and x != None])) tMasterCustomer.masterCustomerList += list(set([str(x) for x in tMcCustomerList if x != '' and x != None])) ############################################################################################################################################## elif(len(tMasterCustomerList) == 1): tMC = tMasterCustomerList[0] #if(len(tMC.masterEmailList) > 0): #tMasterCustomer.masterEmailList += list(set([x for x in tMC.masterEmailList if x != '' and x != None])) #if(len(tMC.masterPhoneList) > 0): #tMasterCustomer.masterPhoneList += list(set([x for x in tMC.masterPhoneList if x != '' and x != None])) #if(len(tMC.masterIpList) > 0): #tMasterCustomer.masterIpList += list(set([x for x in tMC.masterIpList if x != '' and x != None])) #if(len(tMC.masterRsnList) > 0): #tMasterCustomer.masterRsnList += list(set([str(x).strip().lower().replace('-','_').replace(' ','_') for x in tMC.masterRsnList if x != '' and x != None])) #if(len(tMC.masterPaypalIdList) > 0): #tMasterCustomer.masterPaypalIdList += list(set([x for x in tMC.masterPaypalIdList if x != '' and x != None])) tMC.masterEmailList += [tEmail] tMC.masterIpList += tIpList tMC.masterPaypalIdList += tPaypalList tMC.masterPhoneList += [tPhone] tMC.masterRsnList += tRsnList tMasterCustomer.masterEmailList += list(set([x for x in tMC.masterEmailList if x != '' and x != None])) tMasterCustomer.masterPhoneList += list(set([x for x in tMC.masterPhoneList if x != '' and x != None])) tMasterCustomer.masterIpList += list(set([x for x in tMC.masterIpList if x != '' and x != None])) tMasterCustomer.masterRsnList += list(set([str(x).strip().lower().replace('-','_').replace(' ','_') for x in tMC.masterRsnList if x != '' and x != None])) tMasterCustomer.masterPaypalIdList += list(set([x for x in tMC.masterPaypalIdList if x != '' and x != None])) tMasterCustomer.masterCustomerList += [str(tUnattachedCustomer.key())] tDeletionList = [tMC] ############################################################################################################################################## elif(len(tMasterCustomerList) == 0): if(tMasterCustomer.masterCustomerList == None or len(tMasterCustomer.masterCustomerList) == 0): tTempList = [] try: tTempList.append(str(tUnattachedCustomer.key())) except: tUnattachedCustomer.put() tTempList.append(str(tUnattachedCustomer.key())) tMasterCustomer.masterCustomerList += tTempList if(tMasterCustomer.masterEmailList == None or len(tMasterCustomer.masterEmailList) == 0): tTempList = [] tTempList.append(str(tUnattachedCustomer.customerEmail)) tMasterCustomer.masterEmailList += tTempList if(tMasterCustomer.masterIpList == None or len(tMasterCustomer.masterIpList) == 0): tTempList = [] tTempList += list(set(tUnattachedCustomer.customerIpAddresses)) tMasterCustomer.masterIpList += tTempList if(tMasterCustomer.masterPaypalIdList == None or len(tMasterCustomer.masterPaypalIdList) == 0): tTempList = [] tTempList.append(str(tUnattachedCustomer.customerPaypalId)) tMasterCustomer.masterPaypalIdList += tTempList if(tMasterCustomer.masterPhoneList == None or len(tMasterCustomer.masterPhoneList) == 0): tTempList = [] tTempList.append(str(tUnattachedCustomer.customerPhone)) tMasterCustomer.masterPhoneList += tTempList if(tMasterCustomer.masterRsnList == None or len(tMasterCustomer.masterRsnList) == 0): tTempList = [] tTempList += list(set(tRsnList)) tMasterCustomer.masterRsnList += tTempList if(tUnattachedCustomer.customerIsPaBlacklisted == True): tMasterCustomer.masterIsPaBlacklisted = True if(tUnattachedCustomer.customerIsGlobalBlacklisted == True): tMasterCustomer.masterIsGlobalBlacklisted = True #for tProperty, tValue in tUnattachedCustomer.__dict__.iteritems(): #logging.debug("Customer property " + str(tProperty) + " with value " + str(tValue)) #for tProperty, tValue in tMasterCustomer.__dict__.iteritems(): #logging.debug("Master property " + str(tProperty) + " with value " + str(tValue)) tMaster = CustomerMaster() if(len(tDeletionList) > 0): for tMaster in tDeletionList: tMaster.delete() tMasterKey = tMasterCustomer.put() #update other customers if there's >1 tUnattachedCustomer.customerMaster = str(tMasterKey) tUnattachedCustomer.put() tCustomer = Customer() for tCustomerKey in tMasterCustomer.masterCustomerList: tCustomer = Customer.get(tCustomerKey) tCustomer.customerMaster = str(tMasterKey) tCustomer.put() #logging.debug("Master Key: " + str(tMasterKey))
def GetContext(self): tOrder = Order() tOrderList = [] tOrderAgentPairs = {} tOrderDataDict = {} tPaypalOrder = PaypalOrder() tStringOffset = self.request.get('offset') if (len(tStringOffset) > 0): tOffset = int(tStringOffset) else: tOffset = 0 tOrderQuery = Order.all() tOrderQuery.filter("orderIsGenerated", False) tOrderQuery.order('-orderCreated') tOrderList = tOrderQuery.fetch(10, offset=tOffset) tCurrentEocPrices = PriceContainer.GetCurrentPriceDic() tCurrent07Prices = PriceContainer.GetCurrentPriceDic07() tSkip07 = False if tOrder.orderGoldType != None: if tOrder.orderGoldType in ('eoc', '07') is not True: tOrder.orderGoldType = 'UNKNOWN' else: tOrder.orderGoldType = 'UNKNOWN' for tOrder in tOrderList: 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' #tOrder.orderSimpleGoldAmount = tOrder.orderSimpleGoldAmount + ' ' + str(tOrder.orderGoldType) tOrderAgentPairs[str( tOrder.orderAssignedAgent)] = Agent.GetAgentByEmail( tOrder.orderAssignedAgent).agentNickName if (tOffset == 0): tPrev = tOffset else: tPrev = tOffset - 10 tOffset = tOffset + 10 tNext = tOffset tOffset = str(tOffset) tNext = str(tNext) tPrev = str(tPrev) tAgent = tPaypalOrder.GetAssignedAgent() if (tAgent != "No Agent Online"): tAgent = Agent.GetAgentByEmail(tAgent).agentNickName tContext = { 'orders': tOrderList, 'agents': tOrderAgentPairs, 'next': tNext, 'prev': tPrev, 'offset': tOffset, 'agent': tAgent, } return tContext
def GetContext(self): tUser = self.GetUser() tCustomerList = [] tCustomerOrders = [] tCustomerOrderKeys = [] tOrderData = {} tOrder = Order() tShowSearch = False tCustomerLookup = CustomerHandler() tCustomerKey = urllib.unquote(self.request.get('key')) if(tCustomerKey): tCustomerList.append(tCustomerLookup.GetCustomerByKey(tCustomerKey)) #logging.debug(str(len(tCustomerList))) if (tCustomerList == None or len(tCustomerList) == 0): tShowSearch = True else: tShowSearch = False tCustomer = Customer() tCustomer = tCustomerList[0] #Get date 30 days ago tStartDate = datetime.datetime.now() tIncrement = datetime.timedelta(days = -30) tEndDate = tStartDate + tIncrement tCustomerOrderQuery = Order.all() tCustomerOrderQuery.filter("orderCreated >", tEndDate) tCustomerOrderQuery.filter("orderCustomer", tCustomerKey) 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 = datetime.datetime.now() tIncrement = datetime.timedelta(days = -1) tEndDate = tStartDate + tIncrement tCustomerOrderQuery = Order.all().filter("orderCreated >", tEndDate) tCustomerOrderQuery.filter("orderCustomer", tCustomerKey) 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 = datetime.datetime.now() #tIncrement = datetime.timedelta(days = -15) #tEndDate = tStartDate + tIncrement #tCustomerOrderQuery = Order.all().filter("orderCreated >", tEndDate) #tCustomerOrderQuery.filter("orderCustomer", tCustomerKey) #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) #logging.debug(str(tCustomerKey)) tOrderQuery = Order.all() tOrderQuery.filter("orderCustomer", tCustomerKey) tOrderQuery.order("-orderCreated") tCustomerOrders = tOrderQuery.fetch(20) #logging.debug(str(tCustomerOrders)) tShowSearch = str(tShowSearch) return { 'result': tCustomerList, 'customerorders': tCustomerOrders, 'tOrderData':tOrderData, 'search': tShowSearch, }
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
def GetContext(self): tOrder = Order() tOrderList = [] tOrderAgentPairs = {} tOrderDataDict = {} tPaypalOrder = PaypalOrder() tStringOffset = self.request.get("offset") if len(tStringOffset) > 0: tOffset = int(tStringOffset) else: tOffset = 0 tOrderQuery = Order.all() tOrderQuery.filter("orderIsGenerated", False) tOrderQuery.order("-orderCreated") tOrderList = tOrderQuery.fetch(10, offset=tOffset) tCurrentEocPrices = PriceContainer.GetCurrentPriceDic() tCurrent07Prices = PriceContainer.GetCurrentPriceDic07() tSkip07 = False if tOrder.orderGoldType != None: if tOrder.orderGoldType in ("eoc", "07") is not True: tOrder.orderGoldType = "UNKNOWN" else: tOrder.orderGoldType = "UNKNOWN" for tOrder in tOrderList: 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" # tOrder.orderSimpleGoldAmount = tOrder.orderSimpleGoldAmount + ' ' + str(tOrder.orderGoldType) tOrderAgentPairs[str(tOrder.orderAssignedAgent)] = Agent.GetAgentByEmail( tOrder.orderAssignedAgent ).agentNickName if tOffset == 0: tPrev = tOffset else: tPrev = tOffset - 10 tOffset = tOffset + 10 tNext = tOffset tOffset = str(tOffset) tNext = str(tNext) tPrev = str(tPrev) tAgent = tPaypalOrder.GetAssignedAgent() if tAgent != "No Agent Online": tAgent = Agent.GetAgentByEmail(tAgent).agentNickName tContext = { "orders": tOrderList, "agents": tOrderAgentPairs, "next": tNext, "prev": tPrev, "offset": tOffset, "agent": tAgent, } return tContext