def list_orders(request): webapp_id = request.user.get_profile().webapp_id orders = Order.objects.belong_to(webapp_id).order_by('-created_at') #获取order对应的会员 webapp_user_ids = set([order.webapp_user_id for order in orders]) webappuser2member = Member.members_from_webapp_user_ids(webapp_user_ids) for order in orders: member = webappuser2member.get(order.webapp_user_id, None) if member: order.buyer_name = member.username_for_html order.member_id = member.id else: order.buyer_name = u'未知' order.member_id = 0 order.pay_interface_name = PAYTYPE2NAME.get(order.pay_interface_type, u'') order.statu = get_order_status_text(order.status) if order.payment_time is None: order.pay_time = '' elif datetime.strftime(order.payment_time, '%Y-%m-%d %H:%M:%S') == DEFAULT_CREATE_TIME: order.pay_time = '' else: order.pay_time = datetime.strftime(order.payment_time, '%Y-%m-%d %H:%M:%S') pressed_link = "order" c = RequestContext(request, { 'orders': orders, 'pressed_link': pressed_link, }) return render_to_response('mobile_app/orders.html', c)
def get_openid_list_by_webapp_id(webapp_id): openid_list = [] members = Member.get_members(webapp_id) for member in members: openid = member.member_open_id if openid: openid_list.append(openid) return openid_list
def get_card_num_details(request): """ 微众卡明细页面 """ card_id = request.GET.get('card_id', '') start_date = request.GET.get('start_date', '') end_date = request.GET.get('end_date', '') #处理过滤 filter_value = request.GET.get('filter_value', None) count_per_page = int(request.GET.get('count_per_page', '1')) cur_page = int(request.GET.get('page', '1')) card_orders = get_num_details(card_id, filter_value, start_date, end_date) pageinfo, card_orders = paginator.paginate( card_orders, cur_page, count_per_page, query_string=request.META['QUERY_STRING']) cards = [] for card_order in card_orders: cur_weizoom_card = JsonResponse() order = Order.objects.get(order_id=card_order.order_id) cur_weizoom_card.created_at = card_order.created_at.strftime( '%Y-%m-%d %H:%M:%S') cur_weizoom_card.orderid = order.id cur_weizoom_card.order_id = card_order.order_id cur_weizoom_card.owner = User.objects.get( id=card_order.owner_id).username cur_weizoom_card.money = '%.2f' % card_order.money cur_weizoom_card.remainder = '%.2f' % card_order.remainder #获取order对应的会员 webappuser2member = Member.members_from_webapp_user_ids( [order.webapp_user_id]) #获取order对应的member的显示名 member = webappuser2member.get(order.webapp_user_id, None) if member: cur_weizoom_card.use_name = member.username_for_html else: cur_weizoom_card.use_name = u'未知' cards.append(cur_weizoom_card) response = create_response(200) response.data.items = cards response.data.sortAttr = request.GET.get('sort_attr', '-created_at') response.data.pageinfo = paginator.to_dict(pageinfo) return response.get_response()
def export_card_detail(request): card_id = request.POST.get('card_id', '') filter_value = request.POST.get('filter_value', None) start_date = request.POST.get('start_date', '') end_date = request.POST.get('end_date', '') card_orders = get_num_details(card_id, filter_value, start_date, end_date) members_info = [[u'消费时间', u'订单号', u'渠道', u'消费金额', u'余额', u'使用人']] for card in card_orders: order = Order.objects.get(order_id=card.order_id) created_at = card.created_at order_id = card.order_id channel = User.objects.get(id=card.owner_id).username money = '%.2f' % card.money remainder = '%.2f' % card.remainder #获取order对应的会员 webappuser2member = Member.members_from_webapp_user_ids( [order.webapp_user_id]) #获取order对应的member的显示名 member = webappuser2member.get(order.webapp_user_id, None) if member: use_name = member.username_for_html else: use_name = u'未知' re_h = re.compile('</?\w+[^>]*>') #HTML标签 use_name = re_h.sub('', use_name) #去掉HTML 标签 info_list = [created_at, order_id, channel, money, remainder, use_name] members_info.append(info_list) # return ExcelResponse(members_info,output_name=u'微众卡按卡号统计详细列表'.encode('utf8'),force_csv=False) filename = u'微众卡按卡号统计详细列表.xls' #TODO 上线 加.encode('utf8') url = export_csv(members_info, filename, force_csv=False) response = create_response(200) response.data.url = url response.data.filename = filename return response.get_response()
def api_get(request): #将省份处理成dict id2province = {} provinces = Province.objects.all() for province in provinces: id2province[province.id] = province.name #将省份处理成dict result = [] days = int(request.GET.get("days", "30")) today = datetime.now() pre_date = date2string(get_date_after_days(today, -days)) webapp_id = request.GET.get('webapp_id', None) orders = Order.objects.filter(webapp_id=webapp_id, payment_time__gte=pre_date, status__in=[3, 4, 5]).order_by('-payment_time') webapp_user_ids = set([order.webapp_user_id for order in orders]) from modules.member.models import Member webappuser2member = Member.members_from_webapp_user_ids( webapp_user_ids) for order in orders: # 获取order对应的member的显示名 member = webappuser2member.get(order.webapp_user_id, None) if member: order.buyer_name = member.username_for_html order.member_id = member.id else: order.buyer_name = u'未知' order.member_id = 0 order.province_id = order.area.split('_')[0] #根据订单获取商品 products = mall_api.get_order_products(order) order.province_id = order.area.split('_')[0] if len(order.province_id) > 0: order.province_name = id2province[int(order.province_id)] infor_dict = {} infor_dict["province_name"] = order.province_name infor_dict["username"] = order.buyer_name infor_dict["products"] = [] for product in products: if product["promotion"] and product["promotion"].has_key( "type") and product["promotion"][ "type"] == "premium_sale:premium_product": infor_dict["products"].append({ "promotion_name": product["name"], "count": product["count"] }) else: infor_dict["products"].append({ "name": product["name"], "count": product["count"] }) result.append(infor_dict) response = create_response(200) response.data = {'items': result} #return response.get_response() return response.get_jsonp_response(request)
def api_get(request): store_name = UserProfile.objects.get( user_id=request.manager.id).store_name qrcode_url = get_mp_qrcode_img(request.manager.id) order_ids = json.loads(request.GET.get('order_ids', '[]')) #order_ids = request.GET.get('order_ids', '') orders = Order.objects.filter(id__in=[int(id) for id in order_ids]) webapp_user_ids = set([order.webapp_user_id for order in orders]) from modules.member.models import Member webappuser2member = Member.members_from_webapp_user_ids( webapp_user_ids) order_ids = [order.id for order in orders] # 获得order对应的商品数量 order2productcount = {} for relation in OrderHasProduct.objects.filter( order_id__in=order_ids).order_by('id'): order_id = relation.order_id if order_id in order2productcount: order2productcount[order_id] = order2productcount[order_id] + 1 else: order2productcount[order_id] = 1 # 构造返回的order数据 for order in orders: # 获取order对应的member的显示名 member = webappuser2member.get(order.webapp_user_id, None) if member: order.buyer_name = member.username_for_print else: order.buyer_name = u'未知' order.product_count = order2productcount.get(order.id, 0) # 构造返回的order数据 items = [] for order in orders: products = mall_api.get_order_products(order) for product in products: property_values = [] if product['promotion']: if product['promotion']['type'] == "flash_sale": product['name'] = u"【限时抢购】" + product['name'] elif product['promotion'][ 'type'] == "premium_sale:premium_product": product['name'] = u"【赠品】" + product['name'] if product.has_key('grade_discounted_money' ) and product['grade_discounted_money']: product['name'] = u"【会员优惠】" + product['name'] if product.has_key('custom_model_properties' ) and product['custom_model_properties']: for model in product['custom_model_properties']: property_values.append(model['property_value']) product['property_values'] = '/'.join(property_values) if order.supplier_user_id: product['price'] = product['purchase_price'] product['total_price'] = product[ 'purchase_price'] * product['count'] items.append({ 'id': order.id, 'order_id': order.order_id, 'supplier_user_id': order.supplier_user_id, 'products': products, 'total_price': order.total_purchase_price if order.supplier_user_id else Order.get_order_has_price_number(order), 'order_total_price': float('%.2f' % order.get_total_price()), 'ship_name': order.ship_name, 'ship_address': '%s %s' % (regional_util.get_str_value_by_string_ids( order.area), order.ship_address), 'ship_tel': order.ship_tel, 'buyer_name': order.buyer_name, 'created_at': datetime.strftime(order.created_at, '%Y-%m-%d %H:%M:%S'), 'product_count': order.product_count, 'postage': 0 if order.supplier_user_id else '%.2f' % order.postage, 'save_money': 0 if order.supplier_user_id else float(Order.get_order_has_price_number(order)) + float(order.postage) - float(order.final_price) - float(order.weizoom_card_money), 'pay_money': order.total_purchase_price if order.supplier_user_id else order.final_price + order.weizoom_card_money, }) response = create_response(200) response.data = { 'items': items, 'store_name': store_name, 'qrcode_url': qrcode_url, 'order_count': len(order_ids) } return response.get_response()
def export_cards(request): # filter_value = request.POST.get('filter_value', None) # cards = get_num_cards(filter_value) card_ids = request.POST.get('cards', '') card_ids = json.loads(card_ids) weizoom_cards = WeizoomCard.objects.filter(id__in=card_ids) rule_ids = [card.weizoom_card_rule_id for card in weizoom_cards] rule_id2rule = { rule.id: rule for rule in WeizoomCardRule.objects.filter(id__in=rule_ids) } card_id2card_rule = {} for card in weizoom_cards: rule = rule_id2rule[card.weizoom_card_rule_id] card_id2card_rule[card.id] = { 'weizoom_card_id': card.weizoom_card_id, 'active_card_user_id': card.active_card_user_id, 'rule_money': rule.money, 'status': card.status, 'is_expired': card.is_expired, 'money': card.money, 'use_money': rule.money - card.money, 'name': rule.name, 'card_type': rule.card_type, } card2orders = {} order_ids = set() for order in WeizoomCardHasOrder.objects.filter( card_id__in=card_ids).exclude( order_id__in=['-1', '-2']).order_by('-created_at'): if not card2orders.has_key(order.card_id): card2orders[order.card_id] = { "order_id": [order.order_id], "use_time": order.created_at } else: card2orders[order.card_id]["order_id"].append(order.order_id) order_ids.add(order.order_id) order_id2webapp_user_ids = {} webapp_user_ids = [] for order in Order.objects.filter(order_id__in=list(order_ids)): if not order_id2webapp_user_ids.has_key(order.order_id): order_id2webapp_user_ids[order.order_id] = [order.webapp_user_id] else: order_id2webapp_user_ids[order.order_id].append( order.webapp_user_id) webapp_user_ids.append(order.webapp_user_id) cur_cards = {} all_webappuser2member = Member.members_from_webapp_user_ids( webapp_user_ids) card_id2member = {} for card_id, order_id in card2orders.items(): try: card_id2member[card_id] = all_webappuser2member[ order_id2webapp_user_ids[order_id["order_id"][0]][0]] except: card_id2member[card_id] = "" for k, card in card_id2card_rule.items(): buyer_name = u'' order_count = 0 if card2orders.has_key(k): webapp_user_id = None member = card_id2member.get(k, None) #获取order对应的member的显示名 # member = webappuser2member.get(webapp_user_id, None) if member: buyer_name = member.username_for_html else: buyer_name = u'未知' order_count = len(card2orders[k]['order_id']) card_type = u'' if card['card_type'] == WEIZOOM_CARD_EXTERNAL_USER: card_type = u'外部卡' if card['card_type'] == WEIZOOM_CARD_INTERNAL_USER: card_type = u'内部卡' if card['card_type'] == WEIZOOM_CARD_GIFT_USER: card_type = u'赠品卡' status_str = u'' if card['is_expired']: status_str = u'己过期' else: if card['status'] == WEIZOOM_CARD_STATUS_UNUSED: status_str = u'未使用' if card['status'] == WEIZOOM_CARD_STATUS_USED: status_str = u'使用中' if card['status'] == WEIZOOM_CARD_STATUS_INACTIVE: status_str = u'未激活' if card['status'] == WEIZOOM_CARD_STATUS_EMPTY: status_str = u'己用完' cur_cards[k] = { 'card_id': k, 'weizoom_card_id': card['weizoom_card_id'], 'active_card_user_id': card['active_card_user_id'], 'name': card['name'], 'rule_money': '%.2f' % card['rule_money'], 'status': status_str, 'money': '%.2f' % card['money'], 'use_money': '%.2f' % card['use_money'], 'use_time': card2orders[k]['use_time'] if card2orders.has_key(k) else '', 'card_type': card_type, 'order_count': order_count, 'buyer_name': buyer_name } crad_ids = cur_cards.keys() cards = sorted( cur_cards.items(), lambda x, y: cmp(float(x[1]['use_money']), float(y[1]['use_money'])), reverse=True) members_info = [[ u'卡号', u'面额', u'建卡日期', u'建卡人', u'到期时间', u'领用人', u'领用日期', u'激活日期', u'激活人', u'已消费金额', u'消费时间', u'余额', u'备注' ]] all_nedded_cards = WeizoomCard.objects.filter(id__in=crad_ids) cards_id2card = {c.id: c for c in all_nedded_cards} users = User.objects.all() user_id2username = {} for user in users: user_id2username[user.id] = user.username for ch in cards: card = cards_id2card[ch[0]] weizoom_card_id = ch[1]['weizoom_card_id'] weizoom_card_name = ch[1]['name'] weizoom_card_rule_money = ch[1]['rule_money'] status = ch[1]['status'] money = ch[1]['money'] weizoom_card_type = ch[1]['card_type'] weizoom_card_use_money = ch[1]['use_money'] use_time = ch[1]['use_time'] order_count = ch[1]['order_count'] buyer_name = ch[1]['buyer_name'] created_at = card.created_at.strftime('%Y-%m-%d %H:%M:%S') created_by = 'card_admin' expire_time = card.expired_time.strftime('%Y-%m-%d %H:%M:%S') activated_to = card.activated_to activate_time = card.activated_at.strftime( '%Y-%m-%d %H:%M:%S') if card.activated_at else '' active_user_id = ch[1]['active_card_user_id'] if active_user_id in user_id2username: activated_by = user_id2username[active_user_id] else: activated_by = "" remark = card.remark info_list = [ weizoom_card_id, #卡号 weizoom_card_rule_money, #面值 created_at, #建卡日期 created_by, #建卡人 expire_time, #到期时间 activated_to, #领用人 activate_time, #领用日期 activate_time, #激活日期 activated_by, #激活人 weizoom_card_use_money, #已消费金额 use_time, #消费时间 money, #余额 remark, #注释 ] members_info.append(info_list) # return ExcelResponse(members_info,output_name=u'微众卡按卡号统计列表'.encode('utf8'),force_csv=False) filename = u'微众卡按卡号统计列表.xls' #TODO 上线 加.encode('utf8') url = export_csv(members_info, filename, force_csv=False) response = create_response(200) response.data.url = url response.data.filename = filename return response.get_response()
one_message.id = message.id one_message.weixin_message_id = message.weixin_message_id one_message.is_reply = message.is_reply one_message.message_type = message.message_type one_message.pic_url = message.pic_url one_message.audio_url = message.audio_url one_message.content = emotion.mui_change_emotion_to_img( message.content) one_message.weixin_created_at = __format_datetime( message.weixin_created_at) if message.is_reply: one_message.sender_icon = mpuser_preview_info.image_path one_message.sender_name = mpuser_preview_info.name else: member = Member.get_member_by_weixin_user_id(sender.id) if member: one_message.sender_icon = member.user_icon if len( member.user_icon.strip()) > 0 else DEFAULT_ICON one_message.sender_name = member.username_for_html sender_name_response = one_message.sender_name if one_message.sender_icon != sender.weixin_user_icon: sender.weixin_user_icon = member.user_icon else: one_message.sender_icon = sender.weixin_user_icon if len( sender.weixin_user_icon.strip()) > 0 else DEFAULT_ICON one_message.sender_name = sender.weixin_user_nick_name messages_list_json.append(one_message) response = create_response(200) response.data = messages_list_json
def api_get(request): channel_qrcode_id = request.GET.get('id', None) relations = ChannelQrcodeHasMember.objects.filter( channel_qrcode_id=channel_qrcode_id) setting_id2count = {} member_id2setting_id = {} member_ids = [] for r in relations: member_ids.append(r.member_id) member_id2setting_id[r.member_id] = r.channel_qrcode_id if r.channel_qrcode_id in setting_id2count: setting_id2count[r.channel_qrcode_id] += 1 else: setting_id2count[r.channel_qrcode_id] = 1 webapp_users = WebAppUser.objects.filter(member_id__in=member_ids) webapp_user_id2member_id = dict([(u.id, u.member_id) for u in webapp_users]) webapp_user_ids = set(webapp_user_id2member_id.keys()) orders = Order.by_webapp_user_id(webapp_user_ids).filter( status=ORDER_STATUS_SUCCESSED).order_by('-created_at') # 进行分页 count_per_page = int(request.GET.get('count_per_page', 15)) cur_page = int(request.GET.get('page', '1')) pageinfo, orders = paginator.paginate( orders, cur_page, count_per_page, query_string=request.META['QUERY_STRING']) # 获取order对应的会员 webapp_user_ids = set([order.webapp_user_id for order in orders]) from modules.member.models import Member webappuser2member = Member.members_from_webapp_user_ids( webapp_user_ids) # 获得order对应的商品数量 order_ids = [order.id for order in orders] order2productcount = {} for relation in OrderHasProduct.objects.filter(order_id__in=order_ids): order_id = relation.order_id if order_id in order2productcount: order2productcount[order_id] = order2productcount[order_id] + 1 else: order2productcount[order_id] = 1 # 构造返回的order数据 items = [] today = datetime.today() for order in orders: # 获取order对应的member的显示名 member = webappuser2member.get(order.webapp_user_id, None) if member: order.buyer_name = member.username_for_html else: order.buyer_name = u'未知' items.append({ 'id': order.id, 'order_id': order.order_id, 'status': util.get_order_status_text(order.status), 'total_price': order.final_price, 'ship_name': order.ship_name, 'buyer_name': order.buyer_name, 'pay_interface_name': PAYTYPE2NAME.get(order.pay_interface_type, u''), 'created_at': datetime.strftime(order.created_at, '%m-%d %H:%M'), 'product_count': order2productcount.get(order.id, 0), # 'products': product_items, 'customer_message': order.customer_message }) response = create_response(200) response.data = { 'items': items, 'sortAttr': request.GET.get('sort_attr', '-created_at'), 'pageinfo': paginator.to_dict(pageinfo), } return response.get_response()
def mui_get_additional_histories(request): end_id = request.GET['end_id'] session_id = request.GET['s_id'] current_page = 1 count = int(request.GET.get('count', 10)) isManager = request.GET.get('isManager', 'false') isSystemMenager = request.GET.get('isSystemMenager', 'false') # user_id = request.GET['user_id'] session = Session.objects.get(id=session_id) messages = Message.objects.filter(session=session_id).order_by('-id') #进行分页 pageinfo, messages = paginator.paginate(messages, current_page, count) sender_usernames = [m.from_weixin_user_username for m in messages] recevier_usernames = [m.to_weixin_user_username for m in messages] weixin_user_usernames = set(sender_usernames + recevier_usernames) weixin_users = WeixinUser.objects.filter( username__in=weixin_user_usernames) username2weixin_user = dict([u.username, u] for u in weixin_users) mpuser = get_system_user_binded_mpuser(request.user) try: mpuser_preview_info = MpuserPreviewInfo.objects.get(mpuser=mpuser) except: response = create_response(500) response.errMsg = u'获取公众号预览信息失败' return response.get_jsonp_response(request) if isManager == "false" and isSystemMenager == "false": #清空未读消息 Session.objects.filter(mpuser=mpuser, id=session_id).update(unread_count=0) sender_name_response = "" messages_list_json = [] is_active = True if datetime.now( ) < session.latest_contact_created_at + timedelta( hours=EXPIRED_TIME) and datetime.now( ) > session.latest_contact_created_at else False r_messages = [] for message in messages: if message.id == end_id: break else: r_messages.append(message) if not r_messages: response = create_response(500) return response.get_jsonp_response(request) for message in reversed(r_messages): sender = username2weixin_user[message.from_weixin_user_username] one_message = JsonResponse() one_message.id = message.id one_message.weixin_message_id = message.weixin_message_id one_message.is_reply = message.is_reply one_message.message_type = message.message_type one_message.pic_url = message.pic_url one_message.audio_url = message.audio_url one_message.content = emotion.mui_change_emotion_to_img( message.content) one_message.weixin_created_at = __format_datetime( message.weixin_created_at) if message.is_reply: one_message.sender_icon = mpuser_preview_info.image_path one_message.sender_name = mpuser_preview_info.name else: member = Member.get_member_by_weixin_user_id(sender.id) if member: one_message.sender_icon = member.user_icon if len( member.user_icon.strip()) > 0 else DEFAULT_ICON one_message.sender_name = member.username_for_html sender_name_response = one_message.sender_name if one_message.sender_icon != sender.weixin_user_icon: sender.weixin_user_icon = member.user_icon else: one_message.sender_icon = sender.weixin_user_icon if len( sender.weixin_user_icon.strip()) > 0 else DEFAULT_ICON one_message.sender_name = sender.weixin_user_nick_name messages_list_json.append(one_message) response = create_response(200) response.data = messages_list_json response.is_login = True response.is_active = is_active response.session_id = session_id response.weixin_user_id = session.weixin_user_id response.pressed_link = 'message' response.send_user_name = sender_name_response if sender_name_response != "" else session.weixin_user.weixin_user_nick_name response.page_info = __package_pageinfo(pageinfo) response.r_messages_count = len(r_messages) return response.get_jsonp_response(request)
def __get_default_sample_space_size(webapp_id): return Member.count(webapp_id) * 2
def get_session_histories(request, session_id): messages = Message.objects.filter(session=session_id).order_by('-id') sender_usernames = [m.from_weixin_user_username for m in messages] recevier_usernames = [m.to_weixin_user_username for m in messages] weixin_user_usernames = set(sender_usernames + recevier_usernames) weixin_users = WeixinUser.objects.filter( username__in=weixin_user_usernames) username2weixin_user = dict([u.username, u] for u in weixin_users) mpuser = get_system_user_binded_mpuser(request.user) try: mpuser_preview_info = MpuserPreviewInfo.objects.get(mpuser=mpuser) except: response = create_response(500) response.errMsg = u'获取公众号预览信息失败' return response.get_response() #清空未读消息 Session.objects.filter(mpuser=mpuser, id=session_id).update(unread_count=0) messages_list = [] session = Session.objects.get(id=session_id) is_active = True if datetime.now( ) < session.latest_contact_created_at + timedelta( hours=EXPIRED_TIME) and datetime.now( ) > session.latest_contact_created_at else False for message in messages: sender = username2weixin_user[message.from_weixin_user_username] one_message = { 'id': message.id, 'weixin_message_id': message.weixin_message_id, 'is_reply': message.is_reply, 'content': emotion.change_emotion_to_img(message.content), 'weixin_created_at': __format_datetime(message.weixin_created_at) } if message.is_reply: one_message['sender_icon'] = mpuser_preview_info.image_path one_message['sender_name'] = mpuser_preview_info.name else: member = Member.get_member_by_weixin_user_id(sender.id) if member: one_message['sender_icon'] = member.user_icon if len( member.user_icon.strip()) > 0 else DEFAULT_ICON one_message['sender_name'] = member.username_for_html if one_message['sender_icon'] != sender.weixin_user_icon: sender.weixin_user_icon = member.user_icon else: one_message['sender_icon'] = sender.weixin_user_icon if len( sender.weixin_user_icon.strip()) > 0 else DEFAULT_ICON one_message['sender_name'] = sender.weixin_user_nick_name messages_list.append(one_message) wei = Session.objects.get(mpuser=mpuser, id=session_id) c = RequestContext( request, { 'is_login': True, 'is_active': is_active, 'sessions': messages_list, 'session_id': session_id, 'weixin_user_id': wei.weixin_user_id, 'pressed_link': 'messages' }) return render_to_response('mobile_app/list_histories.html', c)
def _export_orders_json(request, order_list, params): # debug # pre_page = 500 # test_index = 0 # begin_time = time.time() status = { '0': u'待支付', '1': u'已取消', '2': u'已支付', '3': u'待发货', '4': u'已发货', '5': u'已完成', '6': u'退款中', '7': u'退款完成', } payment_type = { '-1': u'', '0': u'支付宝', '2': u'微信支付', '3': u'微众卡支付', '9': u'货到付款', '10': u'优惠抵扣' } member_source = {'0': u'直接关注', '1': u'推广扫码', '2': u'会员分享'} # type = ORDER_TYPE2TEXT source_list = {'mine_mall': u'本店', 'weizoom_mall': u'商户'} orders = [[ u'订单号', u'下单时间', u'付款时间', u'商品名称', u'规格', u'商品单价', u'商品数量', u'支付方式', u'支付金额', u'现金支付金额', u'微众卡支付金额', u'运费', u'积分抵扣金额', u'优惠券金额', u'优惠券名称', u'订单状态', u'购买人', u'收货人', u'联系电话', u'收货地址省份', u'收货地址', u'发货人', u'备注', u'来源', u'物流公司', u'快递单号', u'发货时间', u'买家来源', u'买家推荐人' ]] webapp_id = request.user_profile.webapp_id # 订单总量 order_count = len(order_list) finished_order_count = 0 for order in order_list: if order.type != PRODUCT_INTEGRAL_TYPE and order.status == ORDER_STATUS_SUCCESSED: finished_order_count += 1 #商品总额: total_product_money = 0.0 # 订单金额 # total_order_money = 0.0 # 支付金额 final_total_order_money = 0.0 # 微众卡支付金额 weizoom_card_total_order_money = 0.0 # 积分总和 # use_integral_count = 0 # 积分抵扣总金额 use_integral_money = 0.0 #赠品总数 total_premium_product = 0 # 优惠劵价值总和 coupon_money_count = 0 # 直降总金额 # save_money_count = 0 # ##################################### # print 'begin step 1 order_list - '+str(time.time() - begin_time) # order_list = list(order_list.all()) order_ids = [] order_order_ids = [] coupon_ids = [] for o in order_list: order_ids.append(o.id) order_order_ids.append(o.order_id) if o.coupon_id: coupon_ids.append(o.coupon_id) # print 'begin step 2 relations - '+str(time.time() - begin_time) relations = {} product_ids = [] promotion_ids = [] model_value_ids = [] # print 'begin step 2.5 order_list - '+str(time.time() - begin_time) # product_ids = for relation in OrderHasProduct.objects.filter(order__id__in=order_ids): # if test_index % pre_page == pre_page - 1: # print str(test_index) + 's-' +str(time.time() - begin_time) # print relation.order_id # test_index+=1 key = relation.order_id promotion_ids.append(relation.promotion_id) if relations.get(key): relations[key].append(relation) else: relations[key] = [relation] if product_ids.count(relation.product_id) == 0: product_ids.append(relation.product_id) if relation.product_model_name != 'standard': for mod in relation.product_model_name.split('_'): i = mod.find(':') + 1 if i > 0 and re.match('', mod[i:]) and model_value_ids.count( mod[i:]) == 0: model_value_ids.append(mod[i:]) # print 'begin step 3 products - '+str(time.time() - begin_time) id2product = dict([ (product.id, product) for product in Product.objects.filter(id__in=product_ids) ]) # print 'begin step 4 coupons - '+str(time.time() - begin_time) coupon2role = {} role_ids = [] from mall.promotion.models import Coupon, CouponRule for coupon in Coupon.objects.filter(id__in=coupon_ids): coupon2role[coupon.id] = coupon.coupon_rule_id if role_ids.count(coupon.coupon_rule_id) == 0: role_ids.append(coupon.coupon_rule_id) role_id2role = dict([ (role.id, role) for role in CouponRule.objects.filter(id__in=role_ids) ]) # print 'begin step 5 models - '+str(time.time() - begin_time) id2modelname = dict([(str(value.id), value.name) for value in ProductModelPropertyValue.objects.filter( id__in=model_value_ids)]) # print 'end step 6 coupons - '+str(time.time() - begin_time) #获取order对应的会员 webapp_user_ids = set([order.webapp_user_id for order in order_list]) # from modules.member.models import Member webappuser2member = Member.members_from_webapp_user_ids(webapp_user_ids) #++++++++++++++++++++++++++++++members++++++++++++++++++++++++++++++ members = webappuser2member.values() member_self_sub, member_qrcode_and_by_url = [], [] follow_member_ids = [] for member in members: if member.source == SOURCE_SELF_SUB: member_self_sub.append(member) elif member.source in [SOURCE_MEMBER_QRCODE, SOURCE_BY_URL]: member_qrcode_and_by_url.append(member) follow_member_ids.append(member.id) follow_member2father_member = dict([ (relation.follower_member_id, relation.member_id) for relation in MemberFollowRelation.objects.filter( follower_member_id__in=follow_member_ids, is_fans=True) ]) father_member_ids = follow_member2father_member.values() father_member_id2member = dict([ (m.id, m) for m in Member.objects.filter(id__in=father_member_ids) ]) member_id2qrcode = dict([ (relation.member_id, relation) for relation in ChannelQrcodeHasMember.objects.filter( member_id__in=member_self_sub) ]) # print 'end step 6.7 - '+str(time.time() - begin_time) #获取order对应的赠品 order2premium_product = {} order2promotion = dict([ (order_promotion_relation.order_id, order_promotion_relation.promotion_result) for order_promotion_relation in OrderHasPromotion.objects.filter( order_id__in=order_ids, promotion_id__in=promotion_ids, promotion_type='premium_sale') ]) for order_id in order2promotion: temp_premium_products = [] if order2promotion[order_id].has_key('premium_products'): for premium_product in order2promotion[order_id][ 'premium_products']: temp_premium_products.append({ 'name': premium_product['name'], 'count': premium_product['count'], 'price': premium_product['price'] }) order2premium_product[order_id] = temp_premium_products #获取order对应的发货时间 order2postage_time = dict([ (log.order_id, log.created_at.strftime('%Y-%m-%d %H:%M').encode('utf8')) for log in OrderOperationLog.objects.filter( order_id__in=order_order_ids, action="订单发货") ]) # print 'end step 8 order - '+str(time.time() - begin_time) #获取order对应的收货地区 #area = get_str_value_by_string_ids(order.area) for order in order_list: # if test_index % pre_page == 0: # test_begin_time = time.time() # test_index+=1 #获取order对应的member的显示名 member = webappuser2member.get(order.webapp_user_id, None) if member: try: order.buyer_name = member.username_for_html except: # 回避名字解析异常 order.buyer_name = u'未能解析的名字' order.member_id = member.id else: order.buyer_name = u'未知' #获取推荐人的姓名或者带参数二维码的名称 father_name_or_qrcode_name = "" member_source_name = "" before_scanner_qrcode_is_member = "是" SOURCE_SELF_SUB, SOURCE_MEMBER_QRCODE, SOURCE_BY_URL if member.source == SOURCE_SELF_SUB: if member.id in member_id2qrcode.keys( ) and member_id2qrcode[member.id].created_at > order.created_at: member_source_name = "带参数二维码" father_name_or_qrcode_name = member_id2qrcode[ member.id].channel_qrcode.name if member_id2qrcode[member.id].is_new: before_scanner_qrcode_is_member = "否" else: member_source_name = "直接关注" elif member.source == SOURCE_MEMBER_QRCODE: member_source_name = "推广扫码" father_name_or_qrcode_name = father_member_id2member[ follow_member2father_member[member.id]].username_for_html elif member.source == SOURCE_BY_URL: member_source_name = "会员分享" father_name_or_qrcode_name = father_member_id2member[ follow_member2father_member[member.id]].username_for_html else: pass # 计算总和 final_price = 0.0 weizoom_card_money = 0.0 # total_price = order.get_total_price() # use_integral = order.get_use_integral(webapp_id) if order.type == PAY_INTERFACE_COD: if order.status == ORDER_STATUS_SUCCESSED: final_price = order.final_price weizoom_card_money = order.weizoom_card_money final_total_order_money += order.final_price try: coupon_money_count += order.coupon_money weizoom_card_total_order_money += order.weizoom_card_money use_integral_money += order.integral_money except: pass else: if order.status in [2, 3, 4, 5]: final_price = order.final_price weizoom_card_money = order.weizoom_card_money final_total_order_money += order.final_price try: coupon_money_count += order.coupon_money weizoom_card_total_order_money += order.weizoom_card_money use_integral_money += order.integral_money except: pass area = get_str_value_by_string_ids_new(order.area) if area: addr = '%s %s' % (area, order.ship_address) else: addr = '%s' % (order.ship_address) # pay_type = PAYTYPE2NAME.get(order.pay_interface_type, '') if order.order_source: order.come = 'weizoom_mall' else: order.come = 'mine_mall' source = source_list.get(order.come, u'本店') if webapp_id != order.webapp_id: if request.manager.is_weizoom_mall: source = request.manager.username else: source = u'微众商城' orderRelations = relations.get(order.id, []) product_ids = [r.product_id for r in orderRelations] i = 0 for relation in orderRelations: product = id2product[relation.product_id] model_value = '' for mod in relation.product_model_name.split('_'): mod_i = mod.find(':') + 1 if mod_i > 0: model_value += '-' + id2modelname.get(mod[mod_i:], '') else: model_value = '-' # models_name = '' coupon_name = '' coupon_money = '' # promotion_name = '' promotion_type = '' #订单发货时间 postage_time = order2postage_time.get(order.order_id, '') #付款时间 if order.status > ORDER_STATUS_CANCEL and order.payment_time: payment_time = order.payment_time.strftime( '%Y-%m-%d %H:%M').encode('utf8') else: payment_time = '' total_product_money += relation.price * relation.number #save_money_count += relation.total_price - relation.price * relation.number # if relation.promotion_id: # promotion_name = Promotion.objects.get(id=relation.promotion_id).name # promotion_type = Promotion.objects.get(id=relation.promotion_id).type if order.coupon_id: role_id = coupon2role.get(order.coupon_id, None) if role_id: if role_id2role[role_id].limit_product: if role_id2role[ role_id].limit_product_id == relation.product_id: coupon_name = role_id2role[role_id].name + "(单品券)" elif i == 0: coupon_name = role_id2role[role_id].name + "(通用券)" if i == 0: if promotion_type == 1 and "(限时抢购)" not in product.name: product.name = u"(限时抢购)" + product.name if coupon_name: coupon_money = order.coupon_money # type_name = type.get(order.type,'') if area: province = area.split(' ')[0] else: province = u'' temp_leader_names = order.leader_name.split('|') remark = '' j = 1 while j < len(temp_leader_names): remark += temp_leader_names[j] j += 1 order.leader_name = temp_leader_names[0] save_money = str(order.edit_money).replace('.', '').replace( '-', '') if order.edit_money else False orders.append([ '%s%s'.encode('utf8') % (order.order_id, '-%s' % save_money if save_money else ''), order.created_at.strftime('%Y-%m-%d %H:%M').encode('utf8'), payment_time, product.name.encode('utf8'), model_value[1:].encode('utf8'), relation.price, relation.number, payment_type[str( int(order.pay_interface_type))], final_price + weizoom_card_money, final_price, weizoom_card_money, order.postage, order.integral_money, coupon_money, coupon_name, status[str(order.status)].encode('utf8'), order.buyer_name.encode('utf8'), order.ship_name.encode('utf8'), order.ship_tel.encode('utf8'), province.encode('utf8'), addr.encode('utf8'), order.leader_name.encode('utf8'), remark.encode('utf8'), source.encode('utf8'), express_util.get_name_by_value( order.express_company_name).encode('utf8'), order.express_number.encode('utf8'), postage_time, member_source_name, father_name_or_qrcode_name, before_scanner_qrcode_is_member ]) else: if coupon_name: coupon_money = order.coupon_money orders.append([ '%s%s'.encode('utf8') % (order.order_id, '-%s' % save_money if save_money else ''), order.created_at.strftime('%Y-%m-%d %H:%M').encode('utf8'), payment_time, product.name, model_value[1:], relation.price, relation.number, payment_type[str(int(order.pay_interface_type))], u'', u'', u'', u'', u'', coupon_money, coupon_name, status[str(order.status)].encode('utf8'), order.buyer_name.encode('utf8'), order.ship_name.encode('utf8'), order.ship_tel.encode('utf8'), province.encode('utf8'), addr.encode('utf8'), order.leader_name.encode('utf8'), remark.encode('utf8'), source.encode('utf8'), express_util.get_name_by_value( order.express_company_name).encode('utf8'), order.express_number.encode('utf8'), postage_time, member_source_name, father_name_or_qrcode_name, before_scanner_qrcode_is_member ]) i = i + 1 if order.id in order2premium_product: total_premium_product += len(order2premium_product[order.id]) for premium_product in order2premium_product[order.id]: orders.append([ '%s%s'.encode('utf8') % (order.order_id, '-%s' % save_money if save_money else ''), order.created_at.strftime('%Y-%m-%d %H:%M').encode( 'utf8'), payment_time, u'(赠品)' + premium_product['name'], u'', premium_product['price'], premium_product['count'], payment_type[str(int(order.pay_interface_type))], u'', u'', u'', u'', u'', u'', u'', status[str(order.status)].encode('utf8'), order.buyer_name.encode('utf8'), order.ship_name.encode('utf8'), order.ship_tel.encode('utf8'), province.encode('utf8'), addr.encode('utf8'), order.leader_name.encode('utf8'), remark.encode('utf8'), source.encode('utf8'), express_util.get_name_by_value( order.express_company_name).encode('utf8'), order.express_number.encode('utf8'), postage_time, member_source_name, father_name_or_qrcode_name, before_scanner_qrcode_is_member ]) temp_premium_products = [] # if test_index % pre_page == pre_page-1: # print str(test_index)+' - '+str(time.time() - test_begin_time)+'-'+str(time.time() - begin_time) orders.append([ u'总计', u'订单量:' + str(order_count).encode('utf8'), u'已完成:' + str(finished_order_count).encode('utf8'), u'商品金额:' + str(total_product_money).encode('utf8'), u'支付总额:' + str(final_total_order_money + weizoom_card_total_order_money).encode('utf8'), u'现金支付金额:' + str(final_total_order_money).encode('utf8'), u'微众卡支付金额:' + str(weizoom_card_total_order_money).encode('utf8'), u'赠品总数:' + str(total_premium_product).encode('utf8'), u'积分抵扣总金额:' + str(use_integral_money).encode('utf8'), u'优惠劵价值总额:' + str(coupon_money_count).encode('utf8'), #u'直降金额总额:'+str(save_money_count).encode('utf8'), ]) # print 'end - '+str(time.time() - begin_time) return orders
def list_messages(request): # if type(request.user) is not types.IntType : # return render_to_response('mobile_app/list_messages.html') mpuser = get_system_user_binded_mpuser(request.user) if mpuser is None: return render_to_response('mobile_app/list_messages.html') sessions = Session.objects.select_related().filter(mpuser=mpuser, is_show=True) #清空未读消息数量 RealTimeInfo.objects.filter(mpuser=mpuser).update(unread_count=0) weixin_user_usernames = [s.weixin_user_id for s in sessions] weixin_users = WeixinUser.objects.filter( username__in=weixin_user_usernames) username2weixin_user = dict([(u.username, u) for u in weixin_users]) sessions_list = [] for session in sessions: weixin_user = username2weixin_user[session.weixin_user_id] content = emotion.change_emotion_to_img(session.latest_contact_content) if len(content) > 10: content = content[0:10] content = content + '...' one_session = { 'id': session.id, 'sender_fake_id': weixin_user.fake_id, 'sender_username': weixin_user.username, 'sender_name': weixin_user.nickname_for_html, 'weixin_user_icon': weixin_user.weixin_user_icon if len(weixin_user.weixin_user_icon.strip()) > 0 else DEFAULT_ICON, 'content': content, 'created_at': __format_datetime(session.latest_contact_created_at), 'unread_count': session.unread_count, 'is_subscribed': is_subscribed(weixin_user), 'is_active': True if datetime.now() < session.latest_contact_created_at + timedelta(hours=EXPIRED_TIME) and datetime.now() > session.latest_contact_created_at else False } try: member = Member.get_member_by_weixin_user_id(weixin_user.id) if member: one_session.member_id = member.id one_session.member_remarks_name = member.remarks_name if len(member.user_icon.strip()) > 0: one_session.weixin_user_icon = member.user_icon if member.username_for_html: one_session.sender_name = member.username_for_html except: notify_message = u"设置会话信息失败, weixin_user_openid:{}, cause:\n{}".format( session.weixin_user_id, unicode_full_stack()) watchdog_notice(notify_message) # continue sessions_list.append(one_session) # response.data.page_info = __package_pageinfo(pageinfo) c = RequestContext(request, { 'is_login': True, 'sessions': sessions_list, 'pressed_link': 'messages' }) return render_to_response('mobile_app/list_messages.html', c)
def api_get(request): # 时间区间 low_date, high_date, date_range = stats_util.get_date_range(request) start_time = low_date end_time = high_date webapp_id = request.user_profile.webapp_id total_orders = belong_to(webapp_id) qualified_orders = total_orders.prefetch_related( 'orderhasproduct_set').filter( # created_at__gte=start_time, created_at__lt=end_time, created_at__range=(start_time, end_time), status__in=[ models.ORDER_STATUS_PAYED_NOT_SHIP, models.ORDER_STATUS_PAYED_SHIPED, models.ORDER_STATUS_SUCCESSED ]) status_qualified_orders = total_orders.filter(status__in=[ models.ORDER_STATUS_PAYED_NOT_SHIP, models.ORDER_STATUS_PAYED_SHIPED, models.ORDER_STATUS_SUCCESSED ]) pre_status_qualified_orders = status_qualified_orders.filter( created_at__lt=start_time) past_status_qualified_orders = status_qualified_orders.filter( created_at__lt=end_time) #买家来源 buyer_source_stats = { # “直接关注购买”:=∑订单.个数 'sub_source_num': 0, # “推广扫码购买”:=∑订单.个数 'qrcode_source_num': 0, # “分享链接购买”:=∑订单.个数 'url_source_num': 0, # “其他”:=∑订单.个数 'other_source_num': 0 } webapp_user_ids = set( [order.webapp_user_id for order in past_status_qualified_orders]) webappuser2member = Member.members_from_webapp_user_ids( webapp_user_ids) for order in qualified_orders: tmp_member = webappuser2member.get(order.webapp_user_id, None) if tmp_member: if tmp_member.source == SOURCE_SELF_SUB: buyer_source_stats['sub_source_num'] += 1 elif tmp_member.source == SOURCE_MEMBER_QRCODE: buyer_source_stats['qrcode_source_num'] += 1 elif tmp_member.source == SOURCE_BY_URL: buyer_source_stats['url_source_num'] += 1 else: buyer_source_stats['other_source_num'] += 1 else: buyer_source_stats['other_source_num'] += 1 # 系统封装的饼图方法,由于数据次序不统一,故舍弃使用 # return create_pie_chart_response('', # { # "直接关注购买":buyer_source_stats['sub_source_num'], # "推广扫码购买":buyer_source_stats['qrcode_source_num'], # "分享链接购买":buyer_source_stats['url_source_num'], # "其他":buyer_source_stats['other_source_num'] # } # ) response = create_response(200) response.data = { "sub_source_num": buyer_source_stats['sub_source_num'], "qrcode_source_num": buyer_source_stats['qrcode_source_num'], "url_source_num": buyer_source_stats['url_source_num'], "other_source_num": buyer_source_stats['other_source_num'] } return response.get_response()
def api_get(request): # 时间区间 low_date, high_date, date_range = stats_util.get_date_range(request) start_time = low_date end_time = high_date # 用于检查复购订单的辅助List wuid_dict = {'pos': 0} webapp_id = request.user_profile.webapp_id total_orders = belong_to(webapp_id) qualified_orders = total_orders.prefetch_related( 'orderhasproduct_set').filter( # created_at__gte=start_time, created_at__lt=end_time, created_at__range=(start_time, end_time), status__in=[ models.ORDER_STATUS_PAYED_NOT_SHIP, models.ORDER_STATUS_PAYED_SHIPED, models.ORDER_STATUS_SUCCESSED ]) status_qualified_orders = total_orders.filter(status__in=[ models.ORDER_STATUS_PAYED_NOT_SHIP, models.ORDER_STATUS_PAYED_SHIPED, models.ORDER_STATUS_SUCCESSED ]) pre_status_qualified_orders = status_qualified_orders.filter( created_at__lt=start_time) past_status_qualified_orders = status_qualified_orders.filter( created_at__lt=end_time) # 订单总量 order_num = qualified_orders.count() # 重复购买 repeated_num = 0 webapp_user_ids = set( [order.webapp_user_id for order in past_status_qualified_orders]) webappuser2member = Member.members_from_webapp_user_ids( webapp_user_ids) for order in qualified_orders: tmp_member_two = webappuser2member.get(order.webapp_user_id, None) # t0 = time.clock() # t1 = time.time() # print ">>>>>" repeated_num += _get_repeated_num_increment( order.webapp_user_id, wuid_dict, tmp_member_two, webappuser2member, pre_status_qualified_orders) # __report_performance(t0, t1, "repeat counter") # 初次购买 first_buy = order_num - repeated_num # 系统封装的饼图方法,由于数据次序不统一,故舍弃使用 # return create_pie_chart_response('', # { # "重复购买":repeated_num, # "初次购买":first_buy # } # ) response = create_response(200) response.data = {"first_buy": first_buy, "repeated_num": repeated_num} return response.get_response()
def get_channel_details(filter_value, owner_id=None, start_date="", end_date="", cur_page=None, count_per_page=None, query_string=""): if not start_date and owner_id: total_days, start_date, cur_date, end_date = dateutil.get_date_range( dateutil.get_today(), "6", 0) start_date = str(start_date) + ' 00:00:00' end_date = str(end_date) + ' 23:59:59' webapp = WebApp.objects.all() if owner_id: webapp = webapp.filter(owner_id=owner_id) webapp_appids = [] for w in webapp: webapp_appids.append(w.appid) orders = Order.by_webapp_id(webapp_appids).order_by('-created_at') if owner_id: orders = orders.filter(created_at__gte=start_date, created_at__lte=end_date) id2order_ids = {} for r in orders: id2order_ids[r.order_id] = r.id order_ids = id2order_ids.keys() card_orders = WeizoomCardHasOrder.objects.filter( order_id__in=order_ids).order_by('-created_at') #处理过滤 cur_event_type = '0' filter_data_args = {} filter_card_rule_ids = [] if filter_value: filter_data_dict = {} for filter_data_item in filter_value.split('|'): try: key, value = filter_data_item.split(":") except: key = filter_data_item[:filter_data_item.find(':')] value = filter_data_item[filter_data_item.find(':') + 1:] filter_data_dict[key] = value created_at = filter_data_dict['created_at'] if created_at.find('--') > -1: val1, val2 = created_at.split('--') val1 = val1 + ' 00:00:00' val2 = val2 + ' 23:59:59' if owner_id: if val1 < start_date: val1 = start_date if val2 > end_date: val2 = end_date orders = Order.by_webapp_id(webapp_appids).filter( created_at__gte=val1, created_at__lte=val2).order_by('-created_at') order_ids = [] for r in orders: order_ids.append(r.order_id) card_orders = card_orders.filter(order_id__in=order_ids) for key, value in filter_data_dict.items(): #卡号 if key == 'card_id': card_ids = list(card.id for card in WeizoomCard.objects.filter( weizoom_card_id__contains=value)) if card_ids: card_orders = card_orders.filter(card_id__in=card_ids) #卡名称 if key == 'name': rules = WeizoomCardRule.objects.filter(name__contains=value) if rules: for rule in rules: filter_card_rule_ids.append(rule.id) card_ids = list( weizoom_card.id for weizoom_card in WeizoomCard.objects.filter( weizoom_card_rule_id__in=filter_card_rule_ids)) if not filter_data_args.has_key('card_id__in'): # filter_data_args['card_id__in'] = card_ids card_orders = card_orders.filter(card_id__in=card_ids) else: old_card_ids = filter_data_args['card_id__in'] new_card_ids = list( set(old_card_ids).intersection(set(card_ids))) # filter_data_args['card_id__in'] = new_card_ids card_orders = card_orders.filter( card_id__in=new_card_ids) else: filter_data_args["card_id__in"] = -1 #订单号 if key == 'order_id': filter_data_args["order_id__contains"] = value if key == 'member': member_ids = [] for member in Member.objects.filter( username_hexstr__contains=byte_to_hex(value)): member_ids.append(member.id) member_webappuser_ids = [ member.id for member in WebAppUser.objects.filter( member_id__in=member_ids) ] if member_ids: order_ids = list(order.order_id for order in orders.filter( webapp_user_id__in=member_webappuser_ids)) filter_data_args["order_id__in"] = order_ids else: filter_data_args["order_id"] = -1 if key == 'status': if value == "4": card_ids = list(card.id for card in WeizoomCard.objects.filter( is_expired=True)) filter_data_args['card_id__in'] = card_ids else: card_ids = list(card.id for card in WeizoomCard.objects.filter( status=value, is_expired=False)) filter_data_args['card_id__in'] = card_ids if not filter_data_args.has_key('card_id__in'): filter_data_args['card_id__in'] = card_ids else: old_card_ids = filter_data_args['card_id__in'] new_card_ids = list( set(old_card_ids).intersection(set(card_ids))) filter_data_args['card_id__in'] = new_card_ids if key == 'money': val1, val2 = value.split('--') low_money = float(val1) high_money = float(val2) card2money = {} orderids = [] cur_orders = WeizoomCardHasOrder.objects.filter( order_id__in=order_ids) if cur_orders: for order in cur_orders: if not card2money.has_key(order.order_id): if order.event_type == "使用": card2money[order.order_id] = { 'use_money': order.money, 'refund': 0, } else: card2money[order.order_id] = { 'refund': order.money, 'use_money': 0 } else: if order.event_type == "使用": card2money[ order.order_id]['use_money'] += order.money else: card2money[ order.order_id]['refund'] += order.money if card2money: for key, value in card2money.items(): for k, v in value.items(): if v >= low_money and v <= high_money and v != 0: orderids.append(key) if orderids: if not filter_data_args.has_key('order_id__in'): card_orders = card_orders.filter( order_id__in=orderids) else: old_card_ids = filter_data_args['order_id__in'] new_card_ids = list( set(old_card_ids).intersection(set(orderids))) filter_data_args['order_id__in'] = new_card_ids else: filter_data_args['order_id'] = -1 if key == 'event_type': cur_event_type = value if value == '1': orders = orders.filter(status=ORDER_STATUS_CANCEL) order_ids = [] for r in orders: order_ids.append(r.order_id) card_orders = card_orders.filter(order_id__in=order_ids, event_type="返还") if value == '0': # order_ids = [] # for r in orders: # order_ids.append(r.order_id) card_orders = card_orders.filter(order_id__in=order_ids, event_type="使用") card_orders = card_orders.filter(**filter_data_args).exclude( order_id=-1).order_by('-created_at') else: card_orders = card_orders.filter(event_type="使用") # order2card_id = OrderedDict() order2card_id = [] inner_dict = OrderedDict() user_id2username = {u.id: u.username for u in User.objects.all()} for card_order in card_orders.order_by('-created_at'): inner_order_id = card_order.order_id if not inner_dict.has_key(card_order.order_id): if card_order.event_type == "使用": inner_dict[card_order.order_id] = [{ 'order_id': card_order.order_id, 'id': id2order_ids[card_order.order_id], 'card_id': card_order.card_id, 'use_money': '%.2f' % card_order.money, 'created_at': card_order.created_at.strftime('%Y-%m-%d %H:%M:%S'), 'onwer_id': card_order.owner_id, 'owner_username': user_id2username[card_order.owner_id], 'event_type': card_order.event_type }] else: inner_dict[card_order.order_id] = [{ 'order_id': card_order.order_id, 'id': id2order_ids[card_order.order_id], 'card_id': card_order.card_id, 'refund': '%.2f' % -card_order.money, 'created_at': card_order.created_at.strftime('%Y-%m-%d %H:%M:%S'), 'onwer_id': card_order.owner_id, 'owner_username': user_id2username[card_order.owner_id], 'event_type': card_order.event_type }] else: if card_order.event_type == "使用": inner_dict[card_order.order_id].append({ 'card_id': card_order.card_id, 'use_money': '%.2f' % card_order.money, }) else: inner_dict[card_order.order_id].append({ 'card_id': card_order.card_id, 'refund': '%.2f' % -card_order.money, }) temp_list = [] for k, v in inner_dict.items(): temp_list.append({k: v}) order2card_id.append(inner_dict) # order2card_id = sorted(order2card_id.items(), lambda x, y: cmp(x[1][0]['created_at'], y[1][0]['created_at']),reverse=True)order2card_id = sorted(order2card_id.items(), lambda x, y: cmp(x[1][0]['created_at'], y[1][0]['created_at']),reverse=True) if cur_page: pageinfo, temp_list = paginator.paginate(temp_list, cur_page, count_per_page, query_string) key_list = [] for one_dict in temp_list: key_list.append(one_dict.keys()[0]) needed_keys = list(set(inner_dict.keys()) ^ (set(key_list))) for k in needed_keys: del inner_dict[k] order_ids = set() card_ids = set() for inner_dict in order2card_id: # cards = card[1] for order_id, v in inner_dict.items(): for card in v: card_ids.add(card['card_id']) order_ids.add(order_id) order_id2webapp_user_id = {} webapp_user_ids = [] for order in Order.objects.filter(order_id__in=order_ids): order_id2webapp_user_id[order.order_id] = order.webapp_user_id webapp_user_ids.append(order.webapp_user_id) owner_ids = [ user.id for user in User.objects.filter(username__in=['weshop', 'wzjx001']) ] webapp_ids = [ webapp.appid for webapp in WebApp.objects.filter(owner_id__in=owner_ids) ] ids = [] order_id2orderid = {} for order in Order.by_webapp_id(webapp_ids).filter(order_id__in=order_ids): ids.append(order.id) order_id2orderid[order.id] = order.order_id order_order_id2Product_ids = {} product_ids = set() for p in OrderHasProduct.objects.filter(order_id__in=ids): if not order_order_id2Product_ids.has_key(p.product_id): order_order_id2Product_ids[order_id2orderid[p.order_id]] = [ p.product_id ] else: order_order_id2Product_ids[order_id2orderid[p.order_id]].append( p.product_id) product_ids.add(p.product_id) product_id2category_name = {} catetory_id2name = {c.id: c.name for c in ProductCategory.objects.all()} for p in CategoryHasProduct.objects.filter(product_id__in=product_ids): if not product_id2category_name.has_key(p.product_id): product_id2category_name[p.product_id] = [ catetory_id2name[p.category_id] ] else: product_id2category_name[p.product_id].append( catetory_id2name[p.category_id]) weizoom_cards = {} for card in WeizoomCard.objects.filter(id__in=list(card_ids)): status_str = u'' if card.is_expired: status_str = u'己过期' else: if card.status == WEIZOOM_CARD_STATUS_UNUSED: status_str = u'未使用' if card.status == WEIZOOM_CARD_STATUS_USED: status_str = u'使用中' if card.status == WEIZOOM_CARD_STATUS_INACTIVE: status_str = u'未激活' if card.status == WEIZOOM_CARD_STATUS_EMPTY: status_str = u'己用完' weizoom_cards[card.id] = { 'weizoom_card_id': card.weizoom_card_id, 'weizoom_card_rule_id': card.weizoom_card_rule_id, 'status': status_str, } rule_ids = list( set(card['weizoom_card_rule_id'] for card in weizoom_cards.values())) rules = {} for rule in WeizoomCardRule.objects.filter(id__in=rule_ids): rules[rule.id] = { 'rule_name': rule.name, 'rule_money': '%.2f' % rule.money } for card_id in weizoom_cards.keys(): for rule_id in rules.keys(): if weizoom_cards[card_id]['weizoom_card_rule_id'] == rule_id: weizoom_cards[card_id].update(rules[rule_id]) all_webappuser2member = Member.members_from_webapp_user_ids( webapp_user_ids) for inner_dict in order2card_id: for k, orders in inner_dict.items(): # card_orders = order[1] # order_id = order[0] order_id = k product_dict = orders[0]['product'] = {} if order_order_id2Product_ids.has_key(order_id): product_ids = order_order_id2Product_ids[order_id] for one_id in product_ids: try: product_dict[one_id] = ','.join( product_id2category_name[one_id]) except: product_dict[one_id] = '' webapp_user_id = order_id2webapp_user_id[order_id] member = all_webappuser2member[webapp_user_id] if member: buyer_name = member.username_for_html else: buyer_name = u'未知' orders[0].update({'buyer_name': buyer_name}) for card_order in orders: card_id = card_order['card_id'] card_order.update(weizoom_cards[card_id]) if cur_page: return order2card_id, pageinfo, cur_event_type else: return order2card_id
def send_order_export_job_task(self, exportjob_id, filter_data_args, type): export_jobs = ExportJob.objects.filter(id=exportjob_id) status = { '0': u'待支付', '1': u'已取消', '2': u'已支付', '3': u'待发货', '4': u'已发货', '5': u'已完成', '6': u'退款中', '7': u'退款完成', '8': u'退款中', '9': u'退款完成', } payment_type = { '-1': u'', '0': u'支付宝', '2': u'微信支付', '3': u'微众卡支付', '9': u'货到付款', '10': u'优惠抵扣', '11': u'翼支付', '12': u'看购支付', } source_list = {'mine_mall': u'本店', 'weizoom_mall': u'商城'} orders = [ u'订单号', u'下单时间', u'付款时间', u'来源', u'商品名称', u'规格', u'商品单价', u'商品数量', u'销售额', u'商品总重量(斤)', u'支付方式', u'支付金额', u'现金支付金额', u'微众卡', u'运费', u'积分抵扣金额', u'优惠券金额', u'优惠券名称', u'订单状态', u'购买人', u'收货人', u'联系电话', u'收货地址省份', u'收货地址', u'发货人', u'发货人备注', u'物流公司', u'快递单号', u'发货时间', u'商家备注', u'用户备注', u'买家来源', u'买家推荐人', u'扫描带参数二维码之前是否已关注', u'是否首单' ] user_id = filter_data_args["user_id"] status_type = filter_data_args["status_type"] query_dict, date_interval, date_interval_type = filter_data_args[ "query_dict"], filter_data_args["date_interval"], filter_data_args[ "date_interval_type"] order_status = filter_data_args["order_status"] manager_id = filter_data_args["manager_id"] user_profile = UserProfile.objects.get(user_id=user_id) webapp_id = user_profile.webapp_id mall_type = user_profile.webapp_type manager = User.objects.get(id=manager_id) # 查询webapp_type为2的记录(只有一条),用于查询不同平台的供货商数据用 manager2 = UserProfile.objects.get(webapp_type=2) supplier_users = None suplier_not_sub_order_ids = [] if mall_type: # orders[25] = u"供货商" # orders.insert(25, u'供货商类型') orders[3] = u"供货商" # orders.insert(3, u'供货商类型') # orders[12] = u"微众卡支付金额" orders[13] = u"微众卡支付金额" #退现金金额 total_refund_money = 0.0 #退微众卡金额 total_refund_weizoom_card_money = 0.0 #退优惠券金额 total_refund_coupon_money = 0.0 #退积分抵扣金额 total_refund_integral_money = 0.0 for i in [u'退积分抵扣金额', u'退优惠券金额', u'退微众卡金额', u'退现金金额']: # orders.insert(18, i) orders.insert(19, i) # 判断是否有供货商,如果有则显示该字段 has_supplier = False if mall_type: has_supplier = True if has_supplier: orders.append(u'采购价') orders.append(u'采购成本') if type in [1, 3]: filename = "order_{}.xlsx".format(exportjob_id) dir_path_excel = "excel" dir_path = os.path.join(settings.UPLOAD_DIR, dir_path_excel) if not os.path.exists(dir_path): os.makedirs(dir_path) file_path = "{}/{}".format(dir_path, filename) workbook = xlsxwriter.Workbook(file_path) table = workbook.add_worksheet() table.write_row('A1', orders) try: order_list = Order.objects.belong_to(webapp_id).order_by('-id') if status_type: the_one = int(query_dict.get('status', 0)) if status_type == 'refund': tmp_status = [ ORDER_STATUS_REFUNDING, ORDER_STATUS_REFUNDED ] # order_list = order_list.filter(status__in=[ORDER_STATUS_REFUNDING, ORDER_STATUS_REFUNDED]) elif status_type == 'audit': if order_status == '8': tmp_status = [ ORDER_STATUS_GROUP_REFUNDING, ORDER_STATUS_GROUP_REFUNDED ] # order_list = order_list.filter(status__in=[ORDER_STATUS_GROUP_REFUNDING,ORDER_STATUS_GROUP_REFUNDED]) else: tmp_status = [ ORDER_STATUS_REFUNDING, ORDER_STATUS_REFUNDED ] # order_list = order_list.filter(status__in=[ORDER_STATUS_REFUNDING, ORDER_STATUS_REFUNDED]) if query_dict.get('status__in'): tmp_status = [ ORDER_STATUS_GROUP_REFUNDING, ORDER_STATUS_GROUP_REFUNDED ] else: if the_one: tmp_status = [the_one] order_ids_has_refund_sub_orders = get_order_ids_has_refund_sub_orders( webapp_id, tmp_status, mall_type) order_list = order_list.filter( Q(status__in=tmp_status) | Q(id__in=order_ids_has_refund_sub_orders)) if 'status' in query_dict: query_dict.pop('status') else: if query_dict.get('status') and query_dict.get( 'status') == ORDER_STATUS_REFUNDING: tmp_status = [ ORDER_STATUS_GROUP_REFUNDING, ORDER_STATUS_REFUNDING ] _status = int(query_dict.get('status', 0)) if _status: _status = [_status] else: _status = status query_dict.pop('status') order_ids_has_refund_sub_orders = get_order_ids_has_refund_sub_orders( webapp_id, _status, mall_type) order_list = order_list.filter( Q(status__in=tmp_status) | Q(id__in=order_ids_has_refund_sub_orders)) if not mall_type: order_list = order_list.exclude(supplier_user_id__gt=0, status__in=[ ORDER_STATUS_NOT, ORDER_STATUS_CANCEL, ORDER_STATUS_REFUNDING, ORDER_STATUS_REFUNDED ]) product_name = '' if query_dict.get("product_name"): product_name = query_dict["product_name"] # 处理团购筛选 group_order_relations = OrderHasGroup.objects.filter( webapp_id=webapp_id) group_order_ids = [r.order_id for r in group_order_relations] #自营平台有团购了,所以去掉mall_type if query_dict.get('order_type') and query_dict['order_type'] == 2: order_list = order_list.filter(order_id__in=group_order_ids) order_list = get_orders_by_params(query_dict, date_interval, date_interval_type, order_list, user_profile) if product_name: # 订单总量 order_count = len(order_list) finished_order_count = 0 for order in order_list: if order.type != PRODUCT_INTEGRAL_TYPE and order.status == ORDER_STATUS_SUCCESSED: finished_order_count += 1 else: try: order_count = order_list.count() except: order_count = len(order_list) try: finished_order_count = order_list.filter( status=ORDER_STATUS_SUCCESSED).count() except: finished_order_count = len( filter(__filter_order_status, order_list)) # order_list = list(order_list.all()) # -----------------------获取查询条件字典和时间筛选条件--------------构造oreder_list----------结束 # 商品总额: total_product_money = 0.0 # 支付金额 final_total_order_money = 0.0 # 微众卡支付金额 weizoom_card_total_order_money = 0.0 # 积分抵扣总金额 use_integral_money = 0.0 # 赠品总数 total_premium_product = 0 # 优惠劵价值总和 coupon_money_count = 0 ##################################### # print 'begin step 1 order_list - '+str(time.time() - begin_time) order_ids = [] order_order_ids = [] coupon_ids = [] for o in order_list: order_ids.append(o.id) order_order_ids.append(o.order_id) if o.coupon_id: coupon_ids.append(o.coupon_id) coupon2role = {} role_ids = [] from mall.promotion.models import Coupon, CouponRule for coupon in Coupon.objects.filter(id__in=coupon_ids): coupon2role[coupon.id] = coupon.coupon_rule_id if role_ids.count(coupon.coupon_rule_id) == 0: role_ids.append(coupon.coupon_rule_id) role_id2role = dict([ (role.id, role) for role in CouponRule.objects.filter(id__in=role_ids) ]) relations = {} product_ids = [] promotion_ids = [] model_value_ids = [] for relation in OrderHasProduct.objects.filter( order_id__in=order_ids): key = relation.order_id promotion_ids.append(relation.promotion_id) if relations.get(key): relations[key].append(relation) else: relations[key] = [relation] if product_ids.count(relation.product_id) == 0: product_ids.append(relation.product_id) if relation.product_model_name != 'standard': for mod in relation.product_model_name.split('_'): i = mod.find(':') + 1 if i > 0 and re.match( '', mod[i:]) and model_value_ids.count( mod[i:]) == 0: model_value_ids.append(mod[i:]) id2product = dict([ (product.id, product) for product in Product.objects.filter(id__in=product_ids) ]) # print 'begin step 4 coupons - '+str(time.time() - begin_time) # print 'begin step 5 models - '+str(time.time() - begin_time) id2modelname = dict([ (str(value.id), value.name) for value in ProductModelPropertyValue.objects.filter( id__in=model_value_ids) ]) # print 'end step 6 coupons - '+str(time.time() - begin_time) # 获取order对应的会员 webapp_user_ids = set( [order.webapp_user_id for order in order_list]) from modules.member.models import Member webappuser2member = Member.members_from_webapp_user_ids( webapp_user_ids) if webappuser2member: # 构造会员与推荐人或者带参数二维码的关系 members = webappuser2member.values() member_self_sub, member_qrcode_and_by_url = [], [] follow_member_ids = [] all_member_ids = [] for member in members: if member: all_member_ids.append(member.id) if member.source == SOURCE_SELF_SUB: member_self_sub.append(member) elif member.source in [ SOURCE_MEMBER_QRCODE, SOURCE_BY_URL ]: member_qrcode_and_by_url.append(member) follow_member_ids.append(member.id) follow_member2father_member = dict([ (relation.follower_member_id, relation.member_id) for relation in MemberFollowRelation.objects.filter( follower_member_id__in=follow_member_ids, is_fans=True) ]) father_member_ids = follow_member2father_member.values() father_member_id2member = dict([ (m.id, m) for m in Member.objects.filter(id__in=father_member_ids) ]) member_id2qrcode = dict([ (relation.member_id, relation) for relation in ChannelQrcodeHasMember.objects.filter( member_id__in=all_member_ids) ]) order2premium_product = {} order2promotion = dict() for relation in OrderHasPromotion.objects.filter( order_id__in=order_ids, promotion_id__in=promotion_ids, promotion_type='premium_sale'): order2promotion[relation.order_id] = relation.promotion_result order2promotion[ relation.order_id]['promotion_id'] = relation.promotion_id premium_product_ids = [] for order_id in order2promotion: temp_premium_products = [] promotion = order2promotion[order_id] if promotion.get('premium_products'): for premium_product in order2promotion[order_id][ 'premium_products']: temp_premium_products.append({ 'id': premium_product.get('id', ""), 'name': premium_product.get('name', ""), 'count': premium_product.get('count', ""), 'price': premium_product.get('price', ""), 'purchase_price': premium_product.get('purchase_price', 0), }) premium_product_ids.append(premium_product['id']) order2premium_product[order_id] = {} order2premium_product[order_id][ promotion['promotion_id']] = temp_premium_products # 获取商品对应的重量 product_idandmodel_value2weigth = dict([ ((model.product_id, model.name), model.weight) for model in ProductModel.objects.filter( product_id__in=product_ids) ]) # 赠品为单规格 premium_product_id2weight = dict([ (model.product_id, model.weight) for model in ProductModel.objects.filter( product_id__in=premium_product_ids) ]) fackorders = list( Order.objects.filter(origin_order_id__in=order_ids)) if mall_type: order_has_refunds = list( OrderHasRefund.objects.filter( origin_order_id__in=order_ids)) fackorder2refund = {} refund_order_ids = [] for order_has_refund in order_has_refunds: refund_order_ids.append(order_has_refund.origin_order_id) fackorder2refund[ order_has_refund.delivery_item_id] = order_has_refund total_refund_money += order_has_refund.cash total_refund_weizoom_card_money += order_has_refund.weizoom_card_money total_refund_integral_money += order_has_refund.integral_money total_refund_coupon_money += order_has_refund.coupon_money # 获取order对应的供货商 order2supplier2fackorders = {} order2store2fackorders = {} # 取出所有的子订单 for order in fackorders: origin_order_id = order.origin_order_id order2supplier2fackorders.setdefault(origin_order_id, {}) order2store2fackorders.setdefault(origin_order_id, {}) if order.supplier: order2supplier2fackorders[origin_order_id][ order.supplier] = order if order.supplier_user_id: order2store2fackorders[origin_order_id][ order.supplier_user_id] = order # 在order_order_ids中添加子订单 order_order_ids.append(order.order_id) # 获取order对应的发货时间 order2postage_time = dict([ (log.order_id, log.created_at.strftime('%Y-%m-%d %H:%M').encode('utf8')) for log in OrderOperationLog.objects.filter( order_id__in=order_order_ids, action__startswith="订单发货") ]) order2supplier = dict([ (supplier.id, supplier) for supplier in Supplier.objects.filter( owner_id__in=[manager.id, manager2.user_id]) ]) id2store = dict([ (profile.user_id, profile) for profile in UserProfile.objects.filter(webapp_type=0) ]) # print 'end step 8 order - '+str(time.time() - begin_time) # 获取order对应的收货地区 temp_premium_id = None temp_premium_products = [] export_jobs.update(count=order_list.count(), update_at=datetime.now()) tmp_line = 1 write_order_count = 0 tmp_order_id = 0 for order in order_list: # order= __filter_order(order) # 获取order对应的member的显示名 if webappuser2member: member = webappuser2member.get(order.webapp_user_id, None) else: member = None if member: order.buyer_name = handle_member_nickname( member.username_for_html) order.member_id = member.id else: order.buyer_name = u'未知' # 根据用户来源获取用户推荐人或者带参数二维码的名称 father_name_or_qrcode_name = "" member_source_name = "" before_scanner_qrcode_is_member = "" SOURCE_SELF_SUB, SOURCE_MEMBER_QRCODE, SOURCE_BY_URL if member: if member.id in member_id2qrcode.keys(): if member_id2qrcode[ member.id].created_at < order.created_at: member_source_name = "带参数二维码" father_name_or_qrcode_name = member_id2qrcode[ member.id].channel_qrcode.name if member_id2qrcode[member.id].is_new: before_scanner_qrcode_is_member = "否" else: before_scanner_qrcode_is_member = "是" else: if member.source == SOURCE_SELF_SUB: member_source_name = "直接关注" elif member.source == SOURCE_MEMBER_QRCODE: member_source_name = "推广扫码" try: father_name_or_qrcode_name = father_member_id2member[ follow_member2father_member[ member.id]].username_for_html except KeyError: father_name_or_qrcode_name = "" elif member.source == SOURCE_BY_URL: member_source_name = "会员分享" try: father_name_or_qrcode_name = father_member_id2member[ follow_member2father_member[ member.id]].username_for_html except KeyError: father_name_or_qrcode_name = "" else: if member.source == SOURCE_SELF_SUB: member_source_name = "直接关注" elif member.source == SOURCE_MEMBER_QRCODE: member_source_name = "推广扫码" try: father_name_or_qrcode_name = father_member_id2member[ follow_member2father_member[ member.id]].username_for_html except KeyError: father_name_or_qrcode_name = "" elif member.source == SOURCE_BY_URL: member_source_name = "会员分享" try: father_name_or_qrcode_name = father_member_id2member[ follow_member2father_member[ member.id]].username_for_html except KeyError: father_name_or_qrcode_name = "" #----------end--------- # 计算总和 final_price = 0.0 weizoom_card_money = 0.0 if order.status in [2, 3, 4, 5, 6]: final_price = order.final_price weizoom_card_money = order.weizoom_card_money if not mall_type and (order.supplier or order.supplier_user_id): final_total_order_money += order.total_purchase_price else: final_total_order_money += order.final_price try: coupon_money_count += order.coupon_money weizoom_card_total_order_money += order.weizoom_card_money use_integral_money += order.integral_money except: pass elif order.status == 7 and mall_type: if order.id in refund_order_ids: final_price = order.final_price weizoom_card_money = order.weizoom_card_money final_total_order_money += order.final_price weizoom_card_total_order_money += order.weizoom_card_money area = get_str_value_by_string_ids(order.area) if area: province = area.split(' ')[0] address = '%s %s' % (area, order.ship_address) else: province = u'-' address = '%s' % (order.ship_address) if order.order_source: order.come = 'weizoom_mall' else: order.come = 'mine_mall' source = source_list.get(order.come, u'本店') i = 0 # 判断是否订单第一件商品 orderRelations = relations.get(order.id, []) for relation in sorted(orderRelations, key=lambda o: o.id): if temp_premium_id and '%s_%s' % ( order.id, relation.promotion_id) != temp_premium_id: # 添加赠品信息 #orders.extend(temp_premium_products) for temp_premium_product in temp_premium_products: tmp_line += 1 table.write_row("A{}".format(tmp_line), temp_premium_product) temp_premium_products = [] temp_premium_id = None product = id2product[relation.product_id] model_value = '' for mod in relation.product_model_name.split('_'): mod_i = mod.find(':') + 1 if mod_i > 0: model_value += '-' + id2modelname.get( mod[mod_i:], '') else: model_value = '-' # 付款时间 if order.payment_time and DEFAULT_CREATE_TIME != order.payment_time.__str__( ): payment_time = order.payment_time.strftime( '%Y-%m-%d %H:%M').encode('utf8') else: payment_time = '-' # 优惠券和金额 coupon_name = '' coupon_money = '0' if order.coupon_id: role_id = coupon2role.get(order.coupon_id, None) if role_id and i == 0: if role_id2role[role_id].limit_product: coupon_name = role_id2role[ role_id].name + "(多品券)" else: coupon_name = role_id2role[ role_id].name + "(通用券)" if not role_id or coupon_name and order.coupon_money > 0: coupon_money = order.coupon_money fackorder = None fackorder_sons = None if relation.product.supplier: fackorder_sons = order2supplier2fackorders.get( order.id, None) if relation.product.supplier_user_id: fackorder_sons = order2store2fackorders.get( order.id, None) if fackorder_sons: if product.supplier: fackorder = fackorder_sons.get( product.supplier, None) if product.supplier_user_id: fackorder = fackorder_sons.get( product.supplier_user_id, None) save_money = str(order.edit_money).replace( '.', '').replace('-', '') if order.edit_money else False if fackorder: if not '^' in fackorder.order_id: order_id = '%s%s'.encode('utf8') % ( order.order_id if not fackorder else fackorder.order_id, '-%s' % save_money if save_money else '') customer_message = fackorder.customer_message else: order_id = fackorder.order_id customer_message = fackorder.customer_message else: order_id = order.order_id customer_message = order.customer_message #自营下如果商品没有供货商(存在该数据的情况下) order_status = status[ str(order.status if not fackorder else fackorder.status )].encode('utf8') # 订单发货时间 postage_time = order2postage_time.get( order.order_id if not fackorder else fackorder.order_id, '') supplier_type = "" if fackorder: if fackorder.supplier and order2supplier.has_key( fackorder.supplier): source = order2supplier[ fackorder.supplier].name.encode("utf-8") supplier_type = u"自建供货商" if fackorder.supplier_user_id and id2store.has_key( fackorder.supplier_user_id): source = id2store[ fackorder.supplier_user_id].store_name.encode( "utf-8") supplier_type = u"同步供货商" else: if order.supplier and order2supplier.has_key( order.supplier): source = order2supplier[ order.supplier].name.encode("utf-8") supplier_type = u"自建供货商" if order.supplier_user_id and id2store.has_key( order.supplier_user_id): source = id2store[ order.supplier_user_id].store_name.encode( "utf-8") supplier_type = u"同步供货商" if not mall_type and source != u"本店": source = u"商城" if not mall_type and (order.supplier_user_id > 0 or order.supplier > 0): coupon_name = '无' if i == 0: # 发货人处填写的备注 temp_leader_names = (order.leader_name if not fackorder else fackorder.leader_name).split('|') leader_remark = '' j = 1 while j < len(temp_leader_names): leader_remark += temp_leader_names[j] j += 1 order_express_number = ( order.express_number if not fackorder else fackorder.express_number).encode('utf8') express_name = express_util.get_name_by_value( order.express_company_name if not fackorder else fackorder.express_company_name).encode('utf8') tmp_order = [ order_id, order.created_at.strftime('%Y-%m-%d %H:%M').encode( 'utf8'), payment_time, source.encode('utf8'), product.name.encode('utf8'), model_value[1:].encode('utf8'), relation.price, relation.number, relation.price * relation.number, product_idandmodel_value2weigth[ (relation.product_id, relation.product_model_name)] * 2 * relation.number, payment_type[str(int(order.pay_interface_type))], order.total_purchase_price if not mall_type and (order.supplier or order.supplier_user_id) else final_price + weizoom_card_money, u'0' if not mall_type and (order.supplier or order.supplier_user_id) else final_price, u'0' if order.status == 0 else weizoom_card_money, # order.weizoom_card_money_huihui, order.postage, u'0' if order.status == 0 else order.integral_money, u'0' if order.status == 1 and coupon_name else coupon_money, u'无' if order.status == 1 else coupon_name, order_status, order.buyer_name.encode('utf8') if order.buyer_name else '-', order.ship_name.encode('utf8') if order.ship_name else '-', order.ship_tel.encode('utf8') if order.ship_tel else '-', province.encode('utf8') if province else '-', address.encode('utf8') if address else '-', temp_leader_names[0].encode('utf8'), leader_remark.encode('utf8'), # source.encode('utf8'), express_name if express_name else '-', order_express_number if order_express_number else '-', postage_time if postage_time else '-', order.remark.encode('utf8') if order.remark.encode('utf8') else '-', u'-' if customer_message == '' or not customer_message else customer_message.encode('utf-8'), member_source_name if member_source_name else '-', father_name_or_qrcode_name if father_name_or_qrcode_name else '-', before_scanner_qrcode_is_member if before_scanner_qrcode_is_member else '-', u'首单' if order.is_first_order else u'非首单' ] else: order_express_number = ( order.express_number if not fackorder else fackorder.express_number).encode('utf8') express_name = express_util.get_name_by_value( order.express_company_name if not fackorder else fackorder.express_company_name).encode('utf8') tmp_order = [ order_id, order.created_at.strftime('%Y-%m-%d %H:%M').encode( 'utf8'), payment_time, source.encode('utf8'), product.name, model_value[1:], relation.price, relation.number, relation.price * relation.number, product_idandmodel_value2weigth[ (relation.product_id, relation.product_model_name)] * 2 * relation.number, payment_type[str(int(order.pay_interface_type))], u'-', u'-', u'-', # u'-', u'-', u'-', u'-' if order.status == 1 and coupon_name else coupon_money, u'-' if order.status == 1 or not coupon_name else coupon_name, order_status, order.buyer_name.encode('utf8') if order.buyer_name else '-', order.ship_name.encode('utf8') if order.ship_name else '-', order.ship_tel.encode('utf8') if order.ship_tel else '-', province.encode('utf8') if province else '-', address.encode('utf8') if address else '-', temp_leader_names[0].encode('utf8'), leader_remark.encode('utf8'), # source.encode('utf8'), express_name if express_name else '-', order_express_number if order_express_number else '-', postage_time if postage_time else '-', u'-', u'-' if customer_message == '' or not customer_message else customer_message.encode('utf-8'), member_source_name if member_source_name else '-', father_name_or_qrcode_name if father_name_or_qrcode_name else '-', before_scanner_qrcode_is_member if before_scanner_qrcode_is_member else '-', u'首单' if order.is_first_order else u'非首单' ] if mall_type: # tmp_order.insert(25, supplier_type) if fackorder and fackorder2refund.has_key( fackorder.id ) and tmp_order_id != order_id: #供货商相同只在第一列展示 tmp_order.insert( 19, fackorder2refund[fackorder.id].integral_money) tmp_order.insert( 19, fackorder2refund[fackorder.id].coupon_money) tmp_order.insert( 19, fackorder2refund[ fackorder.id].weizoom_card_money) tmp_order.insert( 19, fackorder2refund[fackorder.id].cash) tmp_order_id = order_id else: for i in xrange(4): tmp_order.insert(19, '-') if has_supplier: tmp_order.append(u'-' if 0.0 == product.purchase_price else product.purchase_price) tmp_order.append(u'-' if 0.0 == product.purchase_price else product.purchase_price * relation.number) # orders.append(tmp_order) tmp_line += 1 table.write_row("A{}".format(tmp_line), tmp_order) total_product_money += relation.price * relation.number i += 1 if order.id in order2premium_product and not temp_premium_id: premium_products = order2premium_product[order.id].get( relation.promotion_id, []) # 已取消订单不累计赠品数量 if order_status != STATUS2TEXT[ 1] and order_status != STATUS2TEXT[7]: total_premium_product += len(premium_products) for premium_product in premium_products: order_express_number = ( order.express_number if not fackorder else fackorder.express_number).encode('utf8') express_name = express_util.get_name_by_value( order.express_company_name if not fackorder else fackorder.express_company_name).encode( 'utf8') tmp_order = [ order_id, order.created_at.strftime( '%Y-%m-%d %H:%M').encode('utf8'), payment_time, source.encode('utf8'), u'(赠品)' + premium_product['name'], u'-', premium_product['price'], premium_product['count'], 0.0, premium_product_id2weight[ premium_product['id']] * 2 * relation.number, payment_type[str(int( order.pay_interface_type))], u'-', u'-', u'-', u'-', u'-', u'-', u'-', order_status, order.buyer_name.encode('utf8') if order.buyer_name else '-', order.ship_name.encode('utf8') if order.ship_name else '-', order.ship_tel.encode('utf8') if order.ship_tel else '-', province.encode('utf8') if province else '-', address.encode('utf8') if address else '-', temp_leader_names[0].encode('utf8'), leader_remark.encode('utf8'), # source.encode('utf8'), express_name if express_name else '-', order_express_number if order_express_number else '-', postage_time if postage_time else '-', u'-', u'-', member_source_name if member_source_name else '-', father_name_or_qrcode_name if father_name_or_qrcode_name else '-', before_scanner_qrcode_is_member if before_scanner_qrcode_is_member else '-', '-' ] if mall_type: # tmp_order.insert(25, supplier_type) for i in xrange(4): tmp_order.insert(19, '-') if has_supplier: tmp_order.append( u'-' if 0.0 == premium_product['purchase_price'] else premium_product['purchase_price']) tmp_order.append( u'-' if 0.0 == premium_product['purchase_price'] else premium_product['purchase_price'] * premium_product['count']) temp_premium_products.append(tmp_order) temp_premium_id = '%s_%s' % (order.id, relation.promotion_id) # if test_index % pre_page == pre_page-1: # print str(test_index)+' - '+str(time.time() - test_begin_time)+'-'+str(time.time() - begin_time) write_order_count += 1 export_jobs.update(processed_count=write_order_count, update_at=datetime.now()) if temp_premium_id: # 处理赠品信息 #orders.extend(temp_premium_products) for temp_premium_product in temp_premium_products: tmp_line += 1 table.write_row("A{}".format(tmp_line), temp_premium_product) totals = [ u'总计', u'订单量:' + str(order_count).encode('utf8'), u'已完成:' + str(finished_order_count).encode('utf8'), u'商品金额:' + str(total_product_money).encode('utf8'), u'支付总额:' + str(final_total_order_money + weizoom_card_total_order_money).encode('utf8'), u'现金支付金额:' + str(final_total_order_money).encode('utf8'), u'微众卡支付金额:' + str(weizoom_card_total_order_money).encode('utf8'), u'赠品总数:' + str(total_premium_product).encode('utf8'), u'积分抵扣总金额:' + str(use_integral_money).encode('utf8'), u'优惠劵价值总额:' + str(coupon_money_count).encode('utf8'), ] if mall_type: webapp_type_list = [ u'退现金金额:{}'.format(total_refund_money), u'退微众卡金额:{}'.format(total_refund_weizoom_card_money), u'退优惠券金额:{}'.format(total_refund_coupon_money), u'退积分抵扣金额:{}'.format(total_refund_integral_money), ] totals.extend(webapp_type_list) tmp_line += 1 table.write_row("A{}".format(tmp_line), totals) #return orders workbook.close() upyun_path = '/upload/excel/{}'.format(filename) yun_url = upyun_util.upload_image_to_upyun(file_path, upyun_path) export_jobs.update(status=1, file_path=yun_url, update_at=datetime.now()) except: notify_message = "导出订单任务失败,response:{}".format( unicode_full_stack()) export_jobs.update(status=2, is_download=1) watchdog_error(notify_message)
def _get_stats_data(user, params, is_export): webapp_id = user.get_profile().webapp_id total_orders = belong_to(webapp_id) # time_qualified_orders = total_orders.filter(created_at__gte=params['start_time'], created_at__lt=params['end_time']) status_qualified_orders = total_orders.filter(status__in=[ ORDER_STATUS_PAYED_NOT_SHIP, ORDER_STATUS_PAYED_SHIPED, ORDER_STATUS_SUCCESSED ]) pre_status_qualified_orders = status_qualified_orders.filter( created_at__lt=params['start_time']) past_status_qualified_orders = status_qualified_orders.filter( created_at__lt=params['end_time']) webapp_user_ids = set( [order.webapp_user_id for order in past_status_qualified_orders]) webappuser2member = Member.members_from_webapp_user_ids(webapp_user_ids) # 生成查询对象 # print params q_obj = _create_q(params) # print q_obj # 提前获取所需内容 if params['repeat_buy'] == -1 or params['sort_attr'] == 'id': qualified_orders = total_orders.prefetch_related( 'orderhasproduct_set__product').filter(q_obj).order_by( params['sort_attr']) else: qualified_orders = total_orders.prefetch_related( 'orderhasproduct_set__product').filter(q_obj) wuid_dict = {'pos': 0} items = [] # print 'qualified order num=', qualified_orders.count() for order in qualified_orders: tmp_member = webappuser2member.get(order.webapp_user_id, None) if not _check_buyer_source(params['buyer_source'], tmp_member): continue checked = __check_repeat_buy(params['repeat_buy'], order.webapp_user_id, wuid_dict, tmp_member, webappuser2member, pre_status_qualified_orders) if not checked: continue # clock_t_3 = time.clock() # wall_t_3 = time.time() save_money = float(_get_total_price(order)) + float( order.postage) - float(order.final_price) - float( order.weizoom_card_money) # __report_performance(clock_t_3, wall_t_3, '*****doubt***** part') # clock_t_3 = time.clock() # wall_t_3 = time.time() if is_export: items.append(order) else: member_id = -1 buyer_name = u'未知' if tmp_member: member_id = tmp_member.id try: buyer_name = tmp_member.username_for_html except: buyer_name = u'未能解析的名字' items.append({ 'id': order.id, 'products': _get_products(order), 'order_id': order.order_id, 'save_money': '%.2f' % save_money, 'postage': '%.2f' % order.postage, 'pay_money': '%.2f' % (order.final_price + order.weizoom_card_money), 'pay_interface_type': order.get_pay_interface_name, 'buyer_name': buyer_name, 'member_id': member_id, 'created_at': datetime.strftime(order.created_at, '%Y/%m/%d %H:%M:%S'), 'order_status': order.get_status_text() }) # __report_performance(clock_t_3, wall_t_3, 'doubt part') if params['repeat_buy'] != -1 and params['sort_attr'] == '-id': items.reverse() if is_export: return items return_count = len(items) if params['count_per_page'] > 0: #进行分页 pageinfo, items = paginator.paginate(items, params['cur_page'], params['count_per_page'], params['query_string']) else: #全部订单 pageinfo = {"object_count": return_count} if params.get('sort_attr') == 'id': params['sort_attr'] = 'created_at' if params.get('sort_attr') == '-id': params['sort_attr'] = '-created_at' total_count = status_qualified_orders.count() if total_count > 0: percent = "%.2f%%" % float( float(return_count) / float(total_count) * 100) else: percent = '0.00%' data = { 'items': items, 'pageinfo': paginator.to_dict(pageinfo), 'sortAttr': params['sort_attr'], 'total_count': total_count, 'return_count': return_count, 'percent': percent } return data
def get_num_cards(filter_value, cur_page=None, count_per_page=None, query_string=""): card_relation2orders = WeizoomCardHasOrder.objects.exclude( order_id__in=['-1', '-2']) weizoom_cards = WeizoomCard.objects.all() #处理过滤 filter_data_args = {} start_date = "" end_date = "" if filter_value: filter_data_dict = {} for filter_data_item in filter_value.split('|'): try: key, value = filter_data_item.split(":") except: key = filter_data_item[:filter_data_item.find(':')] value = filter_data_item[filter_data_item.find(':') + 1:] filter_data_dict[key] = value if filter_data_dict.has_key('card_id'): # filter_data_args["weizoom_card_id__contains"] = filter_data_dict['card_id'] weizoom_cards = weizoom_cards.filter( weizoom_card_id__contains=filter_data_dict['card_id']) if filter_data_dict.has_key('name'): rules = WeizoomCardRule.objects.filter( name__contains=filter_data_dict['name']) rule_ids = [] if rules: for rule in rules: rule_ids.append(rule.id) # filter_data_args["weizoom_card_rule_id__in"] = rule_ids weizoom_cards = weizoom_cards.filter( weizoom_card_rule_id__in=rule_ids) else: # filter_data_args["weizoom_card_rule_id"] = -1 weizoom_cards = weizoom_cards.filter(weizoom_card_rule_id=-1) if filter_data_dict.has_key('status'): if filter_data_dict['status'] == "4": weizoom_cards = weizoom_cards.filter(is_expired=True) else: weizoom_cards = weizoom_cards.filter( is_expired=False, status=filter_data_dict['status']) if filter_data_dict.has_key('type'): rules = WeizoomCardRule.objects.filter( card_type=int(filter_data_dict['type'])) if rules: rule_ids = [] for rule in rules: rule_ids.append(rule.id) # filter_data_args["weizoom_card_rule_id__in"] = rule_ids weizoom_cards = weizoom_cards.filter( weizoom_card_rule_id__in=rule_ids) else: # filter_data_args["weizoom_card_rule_id"] = -1 weizoom_cards = weizoom_cards.filter(weizoom_card_rule_id=-1) if filter_data_dict.has_key('created_at'): value = filter_data_dict['created_at'] if value.find('--') > -1: val1, val2 = value.split('--') low_date = val1 + ' 00:00:00' high_date = val2 + ' 23:59:59' weizoom_cards = weizoom_cards.filter(created_at__gte=low_date, created_at__lte=high_date) if filter_data_dict.has_key('activated_at'): value = filter_data_dict['activated_at'] if value.find('--') > -1: val1, val2 = value.split('--') low_date = val1 + ' 00:00:00' high_date = val2 + ' 23:59:59' weizoom_cards = weizoom_cards.filter( activated_at__gte=low_date, activated_at__lte=high_date, status__in=[0, 1, 2, 4]) if filter_data_dict.has_key('used_at'): value = filter_data_dict['used_at'] if value.find('--') > -1: val1, val2 = value.split('--') start_date = val1 + ' 00:00:00' end_date = val2 + ' 23:59:59' card_ids = [] card_relation2orders = card_relation2orders.filter( created_at__gte=start_date, created_at__lte=end_date) card_has_order_dict = {} for one_relation in card_relation2orders: card_ids.append(one_relation.card_id) weizoom_cards = weizoom_cards.filter(id__in=card_ids) if filter_data_dict.has_key('order_id'): value = filter_data_dict['order_id'] card_relation2orders = card_relation2orders.filter( order_id__contains=value) card_ids = [r.card_id for r in card_relation2orders] weizoom_cards = weizoom_cards.filter(id__in=card_ids) if filter_data_dict.has_key('member'): member_ids = [] for member in Member.objects.filter( username_hexstr__contains=byte_to_hex( filter_data_dict['member'])): member_ids.append(member.id) if member_ids: app_users = WebAppUser.objects.filter(member_id__in=member_ids) app_user_ids = [a.id for a in app_users] orders = Order.by_webapp_user_id(app_user_ids) card_ids = [] card_relation2orders = card_relation2orders.filter( order_id__in=[o.order_id for o in orders]) card_has_order_dict = {} for one_relation in card_relation2orders: order_id = one_relation.order_id if not card_has_order_dict.has_key(order_id): card_has_order_dict[order_id] = [one_relation] else: card_has_order_dict[order_id].append(one_relation) for order in orders: for card in card_has_order_dict.get(order.order_id, []): if card: card_ids.append(card.card_id) # filter_data_args["id__in"] = card_ids weizoom_cards = weizoom_cards.filter(id__in=card_ids) else: # filter_data_args["id"] = -1 weizoom_cards = weizoom_cards.filter(id=-1) if filter_data_dict.has_key('money'): val1, val2 = filter_data_dict['money'].split('-') low_money = float(val1) high_money = float(val2) card2money = {} card_relation2orders = card_relation2orders.filter( card_id__in=[card.id for card in weizoom_cards]) cardid2orders = {} for one_order in card_relation2orders: card_id = one_order.card_id if not cardid2orders.has_key(card_id): cardid2orders[card_id] = [one_order] else: cardid2orders[card_id].append(one_order) for weizoom_card in weizoom_cards: orders = cardid2orders.get(weizoom_card.id, []) if orders: for order in orders: if not card2money.has_key(order.card_id): card2money[order.card_id] = order.money else: card2money[weizoom_card.id] += order.money else: card2money[weizoom_card.id] = 0 card_ids = [] for key, value in card2money.items(): if value >= low_money and value <= high_money: card_ids.append(key) # filter_data_args['id__in'] = card_ids weizoom_cards = weizoom_cards.filter(id__in=card_ids) # else: # total_days, low_date, cur_date, high_date = dateutil.get_date_range(dateutil.get_today(), "6", 0) # low_date = str(low_date) + ' 00:00:00' # high_date = str(high_date) + ' 23:59:59' # weizoom_cards = weizoom_cards.filter(created_at__gte=low_date,created_at__lte=high_date) # total_days, low_date, cur_date, high_date = dateutil.get_date_range(dateutil.get_today(), "6", 0) if start_date: start_date = str(start_date) end_date = str(end_date) #获得已经过期的微众卡id today = datetime.today() card_ids_need_expire = [] for card in weizoom_cards: #记录过期并且是未使用的微众卡id if card.expired_time < today: card_ids_need_expire.append(card.id) if len(card_ids_need_expire) > 0: weizoom_cards.filter(id__in=card_ids_need_expire).update( is_expired=True) rule_ids = [card.weizoom_card_rule_id for card in weizoom_cards] rule_id2rule = { rule.id: rule for rule in WeizoomCardRule.objects.filter(id__in=rule_ids) } card_id2card_rule = {} for card in weizoom_cards: rule = rule_id2rule[card.weizoom_card_rule_id] card_id2card_rule[card.id] = { 'weizoom_card_id': card.weizoom_card_id, 'rule_money': rule.money, 'status': card.status, 'is_expired': card.is_expired, 'money': card.money, 'use_money': rule.money - card.money, 'name': rule.name, 'card_type': rule.card_type } card_ids = card_id2card_rule.keys() card_id2card_rule = sorted( card_id2card_rule.items(), lambda x, y: cmp(float(x[1]['use_money']), float(y[1]['use_money'])), reverse=True) if cur_page: pageinfo, card_id2card_rule = paginator.paginate( card_id2card_rule, cur_page, count_per_page, query_string) ids = [card[0] for card in card_id2card_rule] card2orders = {} order_ids = set() for order in card_relation2orders.filter( card_id__in=ids).order_by('-created_at'): if not card2orders.has_key(order.card_id): card2orders[order.card_id] = [order] else: card2orders[order.card_id].append(order) order_ids.add(order.order_id) member2order = {} webapp_user_ids = [] for order in Order.objects.filter(order_id__in=list(order_ids)): member2order[order.order_id] = order.webapp_user_id webapp_user_ids.append(order.webapp_user_id) cur_cards = {} all_webappuser2member = Member.members_from_webapp_user_ids( webapp_user_ids) for card in card_id2card_rule: buyer_name = u'' order_count = 0 if card2orders.has_key(card[0]): for tem_order in card2orders[card[0]]: if member2order.get(tem_order.order_id, None): webapp_user_id = member2order[tem_order.order_id] break member = all_webappuser2member[webapp_user_id] #获取order对应的member的显示名 # member = webappuser2member.get(webapp_user_id, None) if member: buyer_name = member.username_for_html else: buyer_name = u'未知' order_ids = set() for o in card2orders[card[0]]: order_ids.add(o.order_id) order_count = len(order_ids) card_type = u'' if card[1]['card_type'] == WEIZOOM_CARD_EXTERNAL_USER: card_type = u'外部卡' if card[1]['card_type'] == WEIZOOM_CARD_INTERNAL_USER: card_type = u'内部卡' if card[1]['card_type'] == WEIZOOM_CARD_GIFT_USER: card_type = u'赠品卡' status_str = u'' if card[1]['is_expired']: status_str = u'己过期' else: if card[1]['status'] == WEIZOOM_CARD_STATUS_UNUSED: status_str = u'未使用' if card[1]['status'] == WEIZOOM_CARD_STATUS_USED: status_str = u'使用中' if card[1]['status'] == WEIZOOM_CARD_STATUS_INACTIVE: status_str = u'未激活' if card[1]['status'] == WEIZOOM_CARD_STATUS_EMPTY: status_str = u'己用完' cur_cards[card[0]] = { 'card_id': card[0], 'weizoom_card_id': card[1]['weizoom_card_id'], 'name': card[1]['name'], 'rule_money': '%.2f' % card[1]['rule_money'], 'status': status_str, 'money': '%.2f' % card[1]['money'], 'use_money': '%.2f' % card[1]['use_money'], 'card_type': card_type, 'order_count': order_count, 'buyer_name': buyer_name, 'start_date': start_date, 'end_date': end_date } if cur_page: return cur_cards, card_ids, pageinfo else: return cur_cards
def get_order_items(user, order_id, cur_page, order_status=None, found_begin_time=None, found_end_time=None, pay_begin_time=None, pay_end_time=None): if order_id != '': order_list = models.Order.objects.filter( order_id=order_id.strip().split('-')[0]) else: webapp_id = user.get_profile().webapp_id order_list = models.Order.objects.belong_to(webapp_id).order_by( '-id') if order_status != '': order_list = order_list.filter(status=order_status) # 1 下单时间,2 付款时间 if found_begin_time != '' and found_end_time != '': order_list = order_list.filter( created_at__gte=found_begin_time, created_at__lt=found_end_time) if pay_begin_time != '' and pay_end_time != '': order_list = order_list.filter( payment_time__gte=pay_begin_time, payment_time__lt=pay_end_time) # 返回订单的数目 order_return_count = order_list.count() pageinfo, order_list = paginator.paginate(order_list, cur_page, 10) if order_return_count == 0: items = [] return items, pageinfo, order_return_count # 获取order对应的会员 webapp_user_ids = set([order.webapp_user_id for order in order_list]) from modules.member.models import Member webappuser2member = Member.members_from_webapp_user_ids( webapp_user_ids) # 获得order对应的商品数量 order_ids = [order.id for order in order_list] order2productcount = {} for relation in models.OrderHasProduct.objects.filter( order_id__in=order_ids).order_by('id'): order_id = relation.order_id if order_id in order2productcount: order2productcount[order_id] = order2productcount[order_id] + 1 else: order2productcount[order_id] = 1 # 构造返回的order数据 for order in order_list: # 获取order对应的member的显示名 member = webappuser2member.get(order.webapp_user_id, None) if member: order.buyer_name = member.username_for_html #过滤掉表情 if '<span' in order.buyer_name: order.buyer_name = u'未知' else: order.buyer_name = u'未知' if order.payment_time is None: payment_time = '' elif datetime.strftime(order.payment_time, '%Y-%m-%d %H:%M:%S') == DEFAULT_CREATE_TIME: payment_time = '' else: payment_time = datetime.strftime(order.payment_time, '%Y-%m-%d %H:%M:%S') order.product_count = order2productcount.get(order.id, 0) order.payment_time = payment_time # 构造返回的order数据 items = [] for order in order_list: products = mall_api.get_order_products(order) products_result = [] for inner_product in products: product_model_properties = [] if 'custom_model_properties' in inner_product and inner_product[ 'custom_model_properties']: for model in inner_product['custom_model_properties']: return_model = {} return_model['property_value'] = model[ 'property_value'] return_model['name'] = model['name'] product_model_properties.append(return_model) product = { 'total_price': inner_product['total_price'] if 'total_price' in inner_product else inner_product['price'] * inner_product['count'], 'goods_pic': inner_product['thumbnails_url'], 'count': inner_product['count'], 'unit_price': inner_product['price'], 'goods_name': inner_product['name'], 'goods_number': inner_product['user_code'], 'custom_model_properties': product_model_properties } products_result.append(product) regions = regional_util.get_str_value_by_string_ids( order.area).split(" ") items.append({ 'order_id': order.order_id, 'order_status': order.status, 'order_price': float('%.2f' % order.final_price) if order.pay_interface_type != 9 or order.status == 5 else 0, "express_info": { "logistics_number": order.express_number, "buyer_message": order.customer_message, "buyer_name": order.buyer_name, "receiver_name": order.ship_name, "receiver_mobile": order.ship_tel, "receiver_province": regions[0] if len(regions) == 3 else "未知", "receiver_city": regions[1] if len(regions) == 3 else "未知", "receiver_district": regions[2] if len(regions) == 3 else "未知", "receiver_address": order.ship_address, "logistics_name": order.express_company_name }, 'invoice_title': order.bill, 'found_time': datetime.strftime(order.created_at, '%Y-%m-%d %H:%M:%S'), 'num': order.product_count, 'payment_time': order.payment_time, 'pay_mode': order.pay_interface_type, 'store_message': order.remark, 'freight': '%.2f' % order.postage, 'p_price': float(models.Order.get_order_has_price_number(order)) + float(order.postage) - float(order.final_price) - float(order.weizoom_card_money), 'weizoom_card_money': float('%.2f' % order.weizoom_card_money), 'cash': '%.2f' % (order.final_price + order.weizoom_card_money), 'products': products_result }) return items, pageinfo, order_return_count
def get_export_card_data(self): cards = WeizoomCard.objects.filter(weizoom_card_id__startswith='9') card_ids = [card.id for card in cards] order_ids = [ wcho.order_id for wcho in WeizoomCardHasOrder.objects.filter( card_id__in=card_ids).exclude(order_id='-1') ] order_ids = set(order_ids) order_id2cards = {} user_id2username = {u.id: u.username for u in User.objects.all()} orders = Order.objects.filter(order_id__in=list(order_ids)).exclude( status=ORDER_STATUS_REFUNDED) order_id2price = { o.order_id: { "final_price": o.final_price, "price": o.final_price + o.weizoom_card_money, "status": STATUS2TEXT[o.status] } for o in orders } order_id2webapp_user_id = { o.order_id: o.webapp_user_id for o in orders } order_id2id = {o.order_id: o.id for o in orders} id2products = {} for op in OrderHasProduct.objects.filter( order_id__in=order_id2id.values()): if not id2products.has_key(op.order_id): id2products[op.order_id] = [op] else: id2products[op.order_id].append(op) product_ids = [] for products in id2products.values(): for p in products: product_ids.append(p.product_id) prduct_id2producr_name = { p.id: p.name for p in Product.objects.filter(id__in=product_ids) } order_id2product_name = {} for order_id, products in id2products.items(): for p in products: number = u'' if p.number != 1: number = u'(%d)' % p.number if not order_id2product_name.has_key(order_id): order_id2product_name[order_id] = [ u'%s%s' % (prduct_id2producr_name[p.product_id], number) ] else: order_id2product_name[order_id].append( u'%s%s' % (prduct_id2producr_name[p.product_id], number)) webappuser2member = Member.members_from_webapp_user_ids( order_id2webapp_user_id.values()) for order in WeizoomCardHasOrder.objects.filter( order_id__in=list(order_id2price.keys())): if order_id2price.get(order.order_id, None) != None: try: name = webappuser2member[order_id2webapp_user_id[ order.order_id]].username.decode('utf8') except: name = webappuser2member[order_id2webapp_user_id[ order.order_id]].username_hexstr member_created_at = webappuser2member[order_id2webapp_user_id[ order.order_id]].created_at.strftime('%Y-%m-%d %H:%M:%S') if not order_id2cards.has_key(order.order_id): order_id2cards[order.order_id] = [{ 'order_id': order.order_id, 'card_id': order.card_id, 'money': order.money, 'created_at': order.created_at.strftime('%Y-%m-%d %H:%M:%S'), 'onwer_id': order.owner_id, 'owner_username': user_id2username[order.owner_id], 'final_price': order_id2price[order.order_id]['final_price'], 'price': order_id2price[order.order_id]['price'], 'member': name, 'product_name': order_id2product_name[order_id2id[order.order_id]], 'status': order_id2price[order.order_id]['status'], 'member_created_at': member_created_at }] else: order_id2cards[order.order_id].append({ 'order_id': order.order_id, 'card_id': order.card_id, 'money': order.money, 'created_at': order.created_at.strftime('%Y-%m-%d %H:%M:%S'), 'onwer_id': order.owner_id, 'owner_username': user_id2username[order.owner_id], 'final_price': order_id2price[order.order_id]['final_price'], 'price': order_id2price[order.order_id]['price'], 'member': name, 'product_name': order_id2product_name[order_id2id[order.order_id]], 'status': order_id2price[order.order_id]['status'], 'member_created_at': member_created_at }) card_ids = set() for k, inner_list in order_id2cards.items(): for order in inner_list: card_ids.add(order['card_id']) weizoom_cards = {} for card in WeizoomCard.objects.filter(id__in=list(card_ids)): weizoom_cards[card.id] = {'weizoom_card_id': card.weizoom_card_id} members_info = [[ u'订单号', u'用户名', u'消费卡号', u'渠道帐号', u'商品名', u'消费总额', u'微众卡消费消费', u'现金', u'订单的状态', u'消费时间', u'关注时间' ]] for order_id, cards in order_id2cards.items(): for card in cards: card_id = card['card_id'] info_list = [ card['order_id'], card['member'], weizoom_cards[card_id]['weizoom_card_id'], card['owner_username'], ','.join(card['product_name']), '%.2f' % card['price'], '%.2f' % card['money'], '%.2f' % card['final_price'], card['status'].encode('utf-8'), card['created_at'], card['member_created_at'] ] members_info.append(info_list) file_name = os.path.join(settings.UPLOAD_DIR, 'card.xls') wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet(u'微众卡', cell_overwrite_ok=False) row = col = 0 for item in members_info: col = 0 for card in item: ws.write(row, col, card) col += 1 row += 1 print '' print '---- file name: {}'.format(file_name) wb.save(file_name)
def _get_order_items(user, query, filter_value, sort_attr, query_string, count_per_page=15, cur_page=1): webapp_id = user.get_profile().webapp_id orders = Order.objects.belong_to(webapp_id) # # 统计订单总数 # order_total_count = _get_orders_total_count(orders) ################################################### #处理搜索 if query: orders = orders.filter(order_id__icontains=query) ################################################### # 处理筛选条件 source = None if filter_value and (filter_value != '-1'): params, source_value = UserHasOrderFilter.get_filter_params_by_value( filter_value) orders = orders.filter(**params) if source_value == 1: source = 'weizoom_mall' elif source_value == 0: source = 'mine_mall' ################################################### # if user.is_weizoom_mall: # weizoom_mall_order_ids = WeizoomMallHasOtherMallProductOrder.get_orders_weizoom_mall_for_other_mall(webapp_id) # else: # weizoom_mall_order_ids = WeizoomMallHasOtherMallProductOrder.get_order_ids_for(webapp_id) weizoom_orders = Order.by_webapp_id(webapp_id).filter( order_source=ORDER_SOURCE_WEISHOP) weizoom_mall_order_ids = [order.id for order in weizoom_orders] order_id_list = [] if source: for order in orders: if weizoom_mall_order_ids: if order.order_id in weizoom_mall_order_ids: if user.is_weizoom_mall: order.come = 'weizoom_mall' else: order.come = 'weizoom_mall' else: order.come = 'mine_mall' else: order.come = 'mine_mall' if source and order.come != source: continue order_id_list.append(order.id) if order_id_list: orders = orders.filter(id__in=order_id_list) ################################################### #处理排序 if sort_attr != 'created_at': orders = orders.order_by(sort_attr) ################################################### #进行分页 pageinfo, orders = paginator.paginate(orders, cur_page, count_per_page, query_string=query_string) #获取order对应的会员 webapp_user_ids = set([order.webapp_user_id for order in orders]) webappuser2member = Member.members_from_webapp_user_ids(webapp_user_ids) #获得order对应的商品数量 order_ids = [order.id for order in orders] order2productcount = {} for relation in OrderHasProduct.objects.filter(order_id__in=order_ids): order_id = relation.order_id if order_id in order2productcount: order2productcount[order_id] = order2productcount[order_id] + 1 else: order2productcount[order_id] = 1 #构造返回的order数据 items = [] today = datetime.today() for order in orders: #获取order对应的member的显示名 member = webappuser2member.get(order.webapp_user_id, None) if member: order.buyer_name = member.username_for_html order.member_id = member.id else: order.buyer_name = u'未知' order.member_id = 0 payment_time = None if order.payment_time is None: payment_time = '' elif __data_format(order.payment_time) == DEFAULT_CREATE_TIME: payment_time = '' else: payment_time = __data_format(order.payment_time) if weizoom_mall_order_ids: if order.order_id in weizoom_mall_order_ids: if user.is_weizoom_mall: order.come = 'weizoom_mall' else: order.come = 'weizoom_mall' else: order.come = 'mine_mall' else: order.come = 'mine_mall' if source and order.come != source: continue # liupeiyu 该订单中的会员是否可点击 # 来自本店的订单,会员不可点击 # 或者改用户是 微众商城,会员都可点击 if order.come is 'weizoom_mall' and user.is_weizoom_mall is False: order.member_id = 0 order_id_list.append(order.id) items.append({ 'id': order.id, 'order_id': order.order_id, 'status': get_order_status_text(order.status), 'total_price': '%.2f' % order.final_price, 'ship_name': order.ship_name, 'buyer_name': order.buyer_name, 'pay_interface_name': PAYTYPE2NAME.get(order.pay_interface_type, u''), 'created_at': __data_format(order.created_at), 'product_count': order2productcount.get(order.id, 0), 'customer_message': order.customer_message, 'payment_time': payment_time, 'come': order.come, 'member_id': order.member_id, 'type': order.type, 'reason': order.reason }) return items, pageinfo
def get_datas(request,export_id=0): webapp_id = request.user_profile.webapp_id record_id = request.GET.get('record_id', 0) is_show = int(request.GET.get('is_show', 0)) records = app_models.Rebate.objects(id=record_id) rebate_start_time = records[0].start_time rebate_end_time = records[0].end_time # member_id2scan_time = {} # if is_show: # rebate_participances = app_models.RebateParticipance.objects(belong_to=record_id) # member_id2scan_time = {p.member_id: p.created_at for p in rebate_participances} webapp_user_id_belong_to_member_id, id2record, member_id2records, member_id2order_ids, all_orders, member_id2participations = export.get_target_orders(records, is_show) webapp_user_ids = webapp_user_id_belong_to_member_id.keys() params = {'webapp_user_id__in': webapp_user_ids} start_date = request.GET.get('start_date', '') end_date = request.GET.get('end_date', '') start_money = request.GET.get('start_money', 0) end_money = request.GET.get('end_money', 0) is_first_order = int(request.GET.get('is_first_order', 0)) not_first_order = int(request.GET.get('not_first_order', 0)) if is_show: all_orders = all_orders.filter(created_at__gte=rebate_start_time, created_at__lte=rebate_end_time) else: all_orders = all_orders.filter(created_at__lte=rebate_end_time) if start_date: params['created_at__gte'] = start_date if end_date: params['created_at__lte'] = end_date if start_money: params['final_price__gte'] = start_money if end_money: params['final_price__lte'] = end_money if not (is_first_order and not_first_order): if is_first_order: params['is_first_order'] = 1 if not_first_order: params['is_first_order'] = 0 orders = all_orders.filter(**params) #统计微众卡支付总金额和现金支付总金额(退款成功不算) final_price = 0 weizoom_card_money = 0 for order in orders.exclude(status=mall_models.ORDER_STATUS_REFUNDED): final_price += order.final_price weizoom_card_money += order.weizoom_card_money # 进行分页 count_per_page = int(request.GET.get('count_per_page', COUNT_PER_PAGE)) cur_page = int(request.GET.get('page', '1')) if not export_id: pageinfo, orders = paginator.paginate(orders, cur_page, count_per_page,query_string=request.META['QUERY_STRING']) # 获取order对应的会员 webapp_user_ids = set([order.webapp_user_id for order in orders]) webappuser2member = Member.members_from_webapp_user_ids(webapp_user_ids) # 获得order对应的商品数量 order_ids = [order.id for order in orders] order2productcount = {} for relation in mall_models.OrderHasProduct.objects.filter(order_id__in=order_ids): order_id = relation.order_id if order_id in order2productcount: order2productcount[order_id] = order2productcount[order_id] + 1 else: order2productcount[order_id] = 1 items = [] for order in orders: # 获取order对应的member的显示名 member = webappuser2member.get(order.webapp_user_id, None) if member: # if is_show: # member_id = member.id # scan_time = member_id2scan_time.get(member_id, None) # if scan_time and scan_time > order.created_at: # continue order.buyer_name = member.username_for_html order.buyer_id = member.id else: order.buyer_name = u'未知' items.append({ 'id': order.id, 'source': order.order_source, 'order_id': order.order_id, 'status': get_order_status_text(order.status), 'total_price': order.final_price, 'ship_name': order.ship_name, 'buyer_name': order.buyer_name, 'buyer_id': order.buyer_id, 'pay_interface_name': mall_models.PAYTYPE2NAME.get(order.pay_interface_type, u''), 'created_at': datetime.strftime(order.created_at, '%Y-%m-%d %H:%M'), 'payment_time': datetime.strftime(order.payment_time, '%Y-%m-%d %H:%M'), 'product_count': order2productcount.get(order.id, 0), 'products': mall_module_api.get_order_products(order), 'customer_message': order.customer_message, 'order_status': order.status, 'express_company_name': order.express_company_name, 'express_number': order.express_number, 'leader_name': order.leader_name, 'remark': order.remark, 'postage': '%.2f' % order.postage, 'save_money': '%.2f' % (float(mall_models.Order.get_order_has_price_number(order)) + float(order.postage) - float(order.final_price) - float(order.weizoom_card_money)), 'weizoom_card_money': float('%.2f' % order.weizoom_card_money), 'pay_money': '%.2f' % order.final_price, 'is_first_order': order.is_first_order, 'total_purchase_price': order.total_purchase_price #总采购价 }) if not export_id: return pageinfo, items, final_price, weizoom_card_money else: return items