def get_red_envelopes(request): red_envelopes = RedEnvelope.objects.filter(owner=request.user, is_deleted=False) response = create_response(200) #进行分页 count_per_page = int(request.GET.get('count_per_page', 15)) cur_page = int(request.GET.get('page', '1')) pageinfo, red_envelopes = paginator.paginate( red_envelopes, cur_page, count_per_page, query_string=request.META['QUERY_STRING']) response.data.items = [] for red_envelope in red_envelopes: cur_red_envelope = JsonResponse() cur_red_envelope.id = red_envelope.id cur_red_envelope.name = red_envelope.name response.data.items.append(cur_red_envelope) response.data.pageinfo = paginator.to_dict(pageinfo) response.data.sortAttr = request.GET.get('sort_attr', '-created_at') return response.get_response()
def delete_session(request): session_id = request.GET['session_id'] Session.objects.filter(id=session_id).delete() response = JsonResponse() response.code = 200 return response.get_response()
def edit_red_envelope_view(request, id): if int(id) > 0: try: red_envelope = RedEnvelope.objects.get(id=id) except: raise Http404('不存在该微信红包') relations = RedEnvelopeHasPrize.objects.filter(red_envelope=red_envelope) prize_ids = [r.prize_id for r in relations] prizes = Prize.objects.filter(id__in=prize_ids) id2prize = dict([(p.id, p) for p in prizes]) red_envelope.prizes = [] for r in relations: prize = id2prize[r.prize_id] prize.prize_source = r.prize_source prize.prize_type = r.prize_type red_envelope.prizes.append(prize) red_envelope.prizes.sort(lambda x,y: cmp(x.level, y.level)) #转换为json response = JsonResponse() response.id = red_envelope.id response.name = red_envelope.name response.total_award_value = red_envelope.total_award_value response.desc = red_envelope.desc response.can_repeat = red_envelope.can_repeat response.daily_play_count = red_envelope.daily_play_count response.prizes = {} for prize in red_envelope.prizes: prize_json = {} prize_json['prize_source'] = prize.prize_source prize_json['prize_type'] = prize.prize_type prize_json['prize_name'] = prize.name prize_json['prize_level'] = prize.level prize_json['prize_odds'] = prize.odds prize_json['prize_count'] = prize.count response.prizes[prize.id] = prize_json lottery_json = response.get_json() else: red_envelope = {'can_update': True} lottery_json = '' coupon_rules = get_coupon_rules(request.user) c = RequestContext(request, { 'first_nav_name': MARKET_TOOLS_NAV, 'second_navs': export.get_second_navs(request), 'second_nav_name': SECOND_NAV_NAME, 'red_envelope': red_envelope, 'lottery_json':lottery_json, 'coupon_rules':coupon_rules }) return render_to_response('red_envelope/editor/edit_red_envelope.html', c)
def get_weizoom_card_rules(request): count_per_page = int(request.GET.get('count_per_page', '1')) cur_page = int(request.GET.get('page', '1')) weizoom_card_rule_id = int(request.GET.get('weizoom_card_rule_id', '-1')) weizoom_card_rules = WeizoomCardRule.objects.filter(owner=request.user).order_by('-created_at') pageinfo, weizoom_card_rules = paginator.paginate(weizoom_card_rules, cur_page, count_per_page, query_string=request.META['QUERY_STRING']) cur_weizoom_card_rules = [] for c in weizoom_card_rules: cur_weizoom_card_rule = JsonResponse() cur_weizoom_card_rule.id = c.id cur_weizoom_card_rule.name = c.name cur_weizoom_card_rule.count = c.count cur_weizoom_card_rule.remark = c.remark cur_weizoom_card_rule.money = '%.2f' % c.money cur_weizoom_card_rule.expired_time = datetime.strftime(c.expired_time, '%Y-%m-%d %H:%M') cur_weizoom_card_rule.created_at = datetime.strftime(c.created_at, '%Y-%m-%d %H:%M') cur_weizoom_card_rules.append(cur_weizoom_card_rule) response = create_response(200) response.data.items = cur_weizoom_card_rules response.data.sortAttr = request.GET.get('sort_attr', '-created_at') response.data.pageinfo = paginator.to_dict(pageinfo) return response.get_response()
def get_prize(request): webapp_user = request.webapp_user red_envelope_id = int(request.GET['red_envelope_id']) if request.member: member = request.member else: member = None try: red_envelope = RedEnvelope.objects.get(id=red_envelope_id) except: raise Http404(u"该活动信息不存在") response = create_response(200) if webapp_user and RedEnvelopeRecord.objects.filter( owner=red_envelope.owner, webapp_user_id=webapp_user.id, red_envelope=red_envelope).count() > 0: red_envelope_record = RedEnvelopeRecord.objects.filter( owner=red_envelope.owner, webapp_user_id=webapp_user.id, red_envelope=red_envelope)[0] cur_prize = JsonResponse() cur_prize.name = red_envelope_record.prize_name cur_prize.detail = red_envelope_record.prize_detail cur_prize.prize_level = red_envelope_record.prize_level response.data.record_prize = cur_prize else: relations = RedEnvelopeHasPrize.objects.filter( red_envelope=red_envelope) prize_ids = [r.prize_id for r in relations] prizes = Prize.objects.filter(id__in=prize_ids) prizes_count = 0 for prize in prizes: prizes_count = prize.count + prizes_count webapp_id = red_envelope.owner.get_profile().webapp_id sample_space_size = prizes_count # prize = draw_lottery(prizes, webapp_id, sample_space_size=sample_space_size) prize = draw_lottery_new(prizes, webapp_id) red_envelope_record = __record_prize(webapp_user, red_envelope, prize, member) cur_prize = JsonResponse() cur_prize.name = red_envelope_record.prize_name cur_prize.detail = red_envelope_record.prize_detail cur_prize.prize_level = red_envelope_record.prize_level response.data.record_prize = cur_prize # cur_member = JsonResponse() # cur_member.integral = webapp_user.integral_info['count'] # response.data.member = cur_member return response.get_response()
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 get_operation_infos(request): secrect = request.GET.get('secrect', '') from_id = int(request.GET.get('from', 0)) if secrect == 'i@love*tiger(': result = JsonResponse() result.code = 200 result.operations = [] for message in Message.objects.filter(severity=WATCHDOG_OPERATION, id__gt=from_id): operation = JsonResponse() operation.id = message.id operation.message = message.message operation.create_time = message.create_time.strftime('%H:%M') result.operations.append(operation) return result.get_response() else: return HttpResponse('{"code":200, "result":"success"}', 'application/json')
def get_order_list(request): #处理订单号的搜索 query = request.GET.get('query', None).strip() #处理订单状态筛选 filter_value = request.GET.get('filter_value', '-1') #进行分页 cur_page = int(request.GET.get('cur_page', '1')) count_per_page = int(request.GET.get('count', '10')) user = request.user query_string = request.META['QUERY_STRING'] sort_attr = "-created_at" items, pageinfo = _get_order_items(user, query, filter_value, sort_attr, query_string, count_per_page, cur_page) if not items: response = create_response(500) response.errMsg = u'没有订单' return response.get_jsonp_response(request) page_json = JsonResponse() page_json.has_next = paginator.to_dict(pageinfo)['has_next'] existed_pay_interfaces = mall_api.get_pay_interfaces_by_user(user) is_weizoom_mall_partner = AccountHasWeizoomCardPermissions.is_can_use_weizoom_card_by_owner_id( request.user.id) if request.user.is_weizoom_mall: is_weizoom_mall_partner = False if is_weizoom_mall_partner or request.user.is_weizoom_mall: is_show_source = True else: is_show_source = False response = create_response(200) response.data = { 'orders': items, 'page_info': paginator.to_dict(pageinfo), 'is_show_source': is_show_source, 'existed_pay_interfaces': existed_pay_interfaces, } return response.get_jsonp_response(request)
def get_shakes(request): shakes = Shake.objects.filter(owner=request.user, is_deleted=False).order_by('-created_at') response = create_response(200) #进行分页 count_per_page = int(request.GET.get('count_per_page', 15)) cur_page = int(request.GET.get('page', '1')) pageinfo, shakes = paginator.paginate(shakes, cur_page, count_per_page, query_string=request.META['QUERY_STRING']) response.data.items = [] for shake_setting in shakes: shake = JsonResponse() shake.id = shake_setting.id shake.name = shake_setting.name response.data.items.append(shake) response.data.pageinfo = paginator.to_dict(pageinfo) response.data.sortAttr = '-created_at' return response.get_response()
def put(request): file = request.FILES.get('Filedata', None) #读取二进制内容 content = [] if file: for chunk in file.chunks(): content.append(chunk) #获取存储图片的目录和文件信息 file_name = RichTextImage.__get_file_name(file.name) store_dir = time.strftime('%Y%m%d') dir_path = os.path.join(settings.UPLOAD_DIR, store_dir) if not os.path.exists(dir_path): os.makedirs(dir_path) file_path = os.path.join(dir_path, file_name) #写图片文件内容 dst_file = open(file_path, 'wb') print >> dst_file, ''.join(content) dst_file.close() #保存图片信息到mysql中 image_path = '/static/upload/%s/%s' % (store_dir, file_name) image = models.Image.objects.create(user=request.user, path=image_path) response = JsonResponse() response.url = image_path response.state = "SUCCESS" response.title = file.name return response.get_response()
def edit_customer(request): if request.GET: customer_id = request.GET.get('customer_id','') customer = Customer.objects.get(id=customer_id) customer_json = JsonResponse() customer_json.id = customer.id customer_json.name = customer.name customer_json.tel_number = customer.tel_number customer_json.plate_number = customer.plate_number customer_json.vehicle_brand = customer.vehicle_brand customer_json.motorcycle_type = customer.motorcycle_type customer_json.mileage = customer.mileage customer_json.adress = customer.adress customer_json.remark = customer.remark response = create_response(200) response.data.customer = customer_json return response.get_jsonp_response(request) elif request.POST: customer_id = request.POST.get('customer_id','') name = request.POST.get('name','') tel_number = request.POST.get('tel_number','') plate_number = request.POST.get('plate_number','') vehicle_brand = request.POST.get('vehicle_brand','') motorcycle_type = request.POST.get('motorcycle_type','') mileage = request.POST.get('mileage','') adress = request.POST.get('adress','') remark = request.POST.get('remark','') Customer.objects.filter(id=customer_id).update( name = name, tel_number = tel_number, plate_number = plate_number, vehicle_brand = vehicle_brand, motorcycle_type = motorcycle_type, mileage = mileage, adress = adress, remark = remark ) response = create_response(200) return response.get_response()
def get_courses(request): shengjing_course_configs = ShengjingCourseConfig.objects.filter( owner=request.user).order_by('-update_time') count_per_page = int(request.GET.get('count_per_page', 15)) cur_page = int(request.GET.get('page', '1')) pageinfo, shengjing_course_configs = paginator.paginate( shengjing_course_configs, cur_page, count_per_page, query_string=request.META['QUERY_STRING']) response = create_response(200) cur_shengjing_course_configs = [] for config in shengjing_course_configs: cur_course_config = JsonResponse() cur_course_config.id = config.id cur_course_config.name = config.name cur_course_config.created_at = config.created_at.strftime('%Y-%m-%d') cur_course_config.update_time = config.update_time.strftime('%Y-%m-%d') cur_shengjing_course_configs.append(cur_course_config) response.data.items = cur_shengjing_course_configs response.data.sortAttr = request.GET.get('sort_attr', '-display_index') response.data.pageinfo = paginator.to_dict(pageinfo) return response.get_response()
def get_store(request): count_per_page = int(request.GET.get('count_per_page', '1')) cur_page = int(request.GET.get('page', '1')) filter_attr = request.GET.get('filter_attr') if filter_attr == 'city': stores =Store.objects.filter(owner=request.user, city=request.GET.get('filter_value')).order_by('-created_at') else: stores = Store.objects.filter(owner=request.user).order_by('-created_at') pageinfo, stores = paginator.paginate(stores, cur_page, count_per_page, query_string=request.META['QUERY_STRING']) cur_stores = [] for c in stores: cur_store = JsonResponse() cur_store.id = c.id cur_store.name = c.name cur_store.city = c.city cur_store.created_at = datetime.strftime(c.created_at, '%Y-%m-%d %H:%M') cur_stores.append(cur_store) cur_citys = list(Store.objects.filter(owner=request.user).values('city').distinct()) response = create_response(200) response.data.items = cur_stores response.data.all_city = cur_citys response.data.sortAttr = request.GET.get('sort_attr', '-created_at') response.data.pageinfo = paginator.to_dict(pageinfo) return response.get_response()
def kuaidi_callback(request): """ 快递100 推送回调接口 """ response = JsonResponse() callback_id = request.GET.get('callbackid', -1) version = request.GET.get('version', '1') order = None if version == '2.0': express = express_models.ExpressHasOrderPushStatus.get(callback_id) else: order = mall_api.get_order_by_id(callback_id) express = express_models.ExpressHasOrderPushStatus.get_by_order(order) data = ExpressCallbackHandle(request, order, express).handle() # response.data = data # response.data['callback_id'] = callback_id # response.data['version'] = version for key,value in data.items(): response.__dict__[key] = value return response.get_response()
def get_prize(request): webapp_user = request.webapp_user lottery_id = int(request.GET['lottery_id']) prize_position = int(request.GET.get('prize_position', 0)) try: lottery = Lottery.objects.get(id=lottery_id) except: raise Http404(u"该活动信息不存在") member = request.member if not member: raise Http404(u"会员信息不存在") relations = LotteryHasPrize.objects.filter(lottery=lottery) prize_ids = [r.prize_id for r in relations] prizes = Prize.objects.filter(id__in=prize_ids) #定义奖项: if lottery.can_repeat: play_times = lottery.daily_play_count else: play_times = 1 #根据发奖规则发奖 prize = _get_prize(lottery, member, prizes) response = create_response(200) prize = __record_prize(webapp_user, lottery, member, prize, prize_position) if prize: cur_prize = JsonResponse() cur_prize.name = prize.name cur_prize.id = prize.id cur_prize.level = prize.level response.data.prize = cur_prize else: response.data.prize = None cur_member = JsonResponse() cur_member.integral = webapp_user.integral_info['count'] response.data.member = cur_member return response.get_response()
def get_card_num_operations(request): """ 微众卡操作记录页面 """ card_id = request.GET.get('card_id', '') w_card = WeizoomCard.objects.filter(weizoom_card_id=card_id) card_operations = WeizoomCardOperationLog.objects.filter( card_id=w_card[0].id).order_by('-created_at') cur_card_operations = [] for cur_card_operation in card_operations: cur_weizoom_card = JsonResponse() cur_weizoom_card.operater_name = cur_card_operation.operater_name cur_weizoom_card.operate_log = cur_card_operation.operate_log cur_weizoom_card.created_at = cur_card_operation.created_at.strftime( '%Y-%m-%d %H:%M:%S') cur_weizoom_card.remark = cur_card_operation.remark cur_weizoom_card.activated_to = cur_card_operation.activated_to cur_weizoom_card.department = cur_card_operation.department cur_card_operations.append(cur_weizoom_card) response = create_response(200) response.data.items = cur_card_operations return response.get_response()
def get_weizoom_cards(request): count_per_page = int(request.GET.get('count_per_page', '1')) cur_page = int(request.GET.get('page', '1')) weizoom_card_rule_id = int(request.GET.get('weizoom_card_rule_id', '-1')) query = request.GET.get('query', None) weizoom_cards = WeizoomCard.objects.filter(owner=request.user, weizoom_card_rule_id=weizoom_card_rule_id) #获得已经过期的微众卡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: WeizoomCard.objects.filter(id__in=card_ids_need_expire).update(is_expired=True) #处理过滤 filter_attr = request.GET.get('filter_attr', None) filter_value = int(request.GET.get('filter_value', -1)) if filter_attr and (filter_value != -1): params = {filter_attr: filter_value} weizoom_cards = weizoom_cards.filter(**params) if query: weizoom_cards = weizoom_cards.filter(weizoom_card_id=query) pageinfo, weizoom_cards = paginator.paginate(weizoom_cards, cur_page, count_per_page, query_string=request.META['QUERY_STRING']) target_user_ids = [] for weizoom_card in weizoom_cards: target_user_ids.append(weizoom_card.target_user_id) card_has_accounts = WeizoomCardHasAccount.objects.filter(owner=request.user, account__in=target_user_ids) user2name = {} for card_has_account in card_has_accounts: user2name[card_has_account.account_id] = card_has_account.account_name cur_weizoom_cards = [] for c in weizoom_cards: cur_weizoom_card = JsonResponse() cur_weizoom_card.id = c.id cur_weizoom_card.status = c.status cur_weizoom_card.weizoom_card_id = c.weizoom_card_id cur_weizoom_card.password = c.password cur_weizoom_card.money = '%.2f' % c.money if c.activated_at: cur_weizoom_card.activated_at = c.activated_at.strftime('%Y-%m-%d %H:%M:%S') else: cur_weizoom_card.activated_at = '' cur_weizoom_card.target_name = user2name.get(c.target_user_id, u'') cur_weizoom_card.is_expired = c.is_expired cur_weizoom_cards.append(cur_weizoom_card) response = create_response(200) response.data.items = cur_weizoom_cards response.data.sortAttr = request.GET.get('sort_attr', '-created_at') response.data.pageinfo = paginator.to_dict(pageinfo) return response.get_response()
def get_order(request): id = request.GET.get('id') order = Order.objects.get(id=id) order_has_products = OrderHasProduct.objects.filter(order=order) number = 0 cur_order = JsonResponse() for order_has_product in order_has_products: number += order_has_product.number cur_order.number = number cur_order.statu = get_order_status_text(order.status) cur_order.express_company_name = get_name_by_value( order.express_company_name) cur_order.type = order.type cur_order.express_number = order.express_number cur_order.leader_name = order.leader_name cur_order.integral = order.integral cur_order.bill_type = order.bill_type cur_order.bill = order.bill cur_order.order_id = order.order_id cur_order.final_price = '%.2f' % order.final_price cur_order.postage = '%.2f' % order.postage cur_order.ship_name = order.ship_name cur_order.ship_tel = order.ship_tel cur_order.area = regional_util.get_str_value_by_string_ids(order.area) cur_order.ship_address = order.ship_address cur_order.customer_message = order.customer_message cur_order.created_at = __data_format(order.created_at) cur_order.action = get_order_actions(order) cur_order.reason = order.reason #关联的优惠券 coupon = order.get_coupon() if coupon: cur_coupon = JsonResponse() cur_coupon.coupon_id = coupon.coupon_id cur_coupon.coupon_rule_name = coupon.coupon_rule.name cur_coupon.money = str(coupon.money) cur_order.coupon = cur_coupon else: cur_order.coupon = None products = mall_api.get_order_products(order) #商品 cur_product_json = [] for product in products: cur_product = JsonResponse() cur_product.name = product['name'] cur_product.count = product['count'] cur_product.total_price = product['total_price'] cur_product.thumbnails_url = product['thumbnails_url'] cur_product.is_deleted = product['is_deleted'] properties = product['custom_model_properties'] if properties: for product_property in properties: cur_product.property_name = product_property['name'] cur_product.property_value = product_property['property_value'] cur_product_json.append(cur_product) response = create_response(200) response.data.order = cur_order response.data.products = cur_product_json return response.get_jsonp_response(request)
def get_member_records(request): activity_id = int(request.GET['activity_id']) activity = Activity.objects.get(id=activity_id) query = request.GET.get('query', None) filter_attr = request.GET.get('filter_attr', None) filter_value = request.GET.get('filter_value', None) is_enable_offline_sign = activity.is_enable_offline_sign weapp_users = activity.joined_weapp_users webapp_user_ids = [user.id for user in weapp_users] weapp_user_id_2_values = {} for item_value in ActivityItemValue.objects.filter( activity=activity, webapp_user_id__in=webapp_user_ids): weapp_user_id_2_values.setdefault(item_value.webapp_user_id, {})[item_value.item_id] = item_value items = list(ActivityItem.objects.filter(activity=activity)) if activity.is_enable_offline_sign: activity_user_codes = ActivityUserCode.objects.filter( activity=activity, webapp_user_id__in=webapp_user_ids) if query: activity_user_codes = activity_user_codes.filter(sign_code=query) #处理过滤 if filter_attr: if filter_value != '-1': activity_user_codes = activity_user_codes.filter( sign_status=int(filter_value)) user_id2code = dict([(a.webapp_user_id, a.sign_code) for a in activity_user_codes]) user_id2sign_status = dict([(a.webapp_user_id, a.sign_status) for a in activity_user_codes]) weapp_users = [user for user in weapp_users if user.id in user_id2code] #进行分页 count_per_page = int(request.GET.get('count_per_page', 15)) cur_page = int(request.GET.get('page', '1')) pageinfo, weapp_users = paginator.paginate( weapp_users, cur_page, count_per_page, query_string=request.META['QUERY_STRING']) response = create_response(200) cur_weapp_users = [] for weapp_user in weapp_users: cur_weapp_user = JsonResponse() cur_weapp_user.id = weapp_user.id member = weapp_user.get_member_by_webapp_user_id(weapp_user.id) if not activity.is_enable_offline_sign and query: if member: if member.username_for_html != query: continue else: continue cur_member = JsonResponse() if member: cur_member.id = member.id cur_member.user_icon = member.user_icon cur_member.username_for_html = member.username_for_html else: cur_member = '' cur_weapp_user.member = cur_member try: sign_code = user_id2code[weapp_user.id] sign_status = user_id2sign_status[weapp_user.id] except: sign_code = '' sign_status = 0 cur_weapp_user.sign_code = sign_code cur_weapp_user.sign_status = sign_status cur_weapp_user.item_values = [] item_values = [] for item in items: id2value = weapp_user_id_2_values[weapp_user.id] if not item.id in id2value: #存在非必填项 continue value = id2value[item.id] user_input_value = value.value is_image = False if item.type == ACTIVITYITEM_TYPE_IMAGE: is_image = True cur_item = JsonResponse() cur_item.title = item.title cur_item.is_image = is_image cur_item.user_input_value = user_input_value item_values.append(cur_item) cur_weapp_user.item_values = item_values cur_weapp_users.append(cur_weapp_user) response.data.weapp_users = cur_weapp_users cur_activity = JsonResponse() cur_activity.id = activity.id cur_activity.name = activity.name cur_activity.start_date = activity.start_date cur_activity.end_date = activity.end_date cur_activity.is_enable_offline_sign = activity.is_enable_offline_sign response.data.activity = cur_activity response.data.pageinfo = paginator.to_dict(pageinfo) response.data.sortAttr = request.GET.get('sort_attr', '-created_at') return response.get_response()
def api_get(request): """ 获取优惠券advanced table """ coupon_code = request.GET.get('couponCode', '') use_status = request.GET.get('useStatus', '') member_name = request.GET.get('memberName', '') #是否显示最后一页 is_max_page = int(request.GET.get('is_max_page', 0)) is_fetch_all_coupon = (not coupon_code) and (use_status == 'all') and ( not member_name) # 处理排序 sort_attr = request.GET.get('sort_attr', '-id') coupon_rule_id = request.GET.get('id') if coupon_rule_id: coupons = Coupon.objects.filter( owner=request.manager, coupon_rule_id=coupon_rule_id).order_by(sort_attr) # 获取coupon所属的rule的name id2rule = dict([ (rule.id, rule) for rule in CouponRule.objects.filter(owner=request.manager) ]) if is_fetch_all_coupon: # 进行分页 count_per_page = int(request.GET.get('count_per_page', 15)) cur_page = int(request.GET.get('page', '1')) pageinfo, coupons = paginator.paginate( coupons, cur_page, count_per_page, query_string=request.META['QUERY_STRING']) else: coupons_data = _filter_reviews(request, coupons) count_per_page = int(request.GET.get('count_per_page', 15)) cur_page = request.GET.get('page', '1') t_max_page = False if cur_page == "true": t_max_page = True cur_page = 1 pageinfo, coupons = paginator.paginate( coupons_data, cur_page, count_per_page, query_string=request.META['QUERY_STRING']) ##是否从最后一页开始显示 if is_max_page: max_page = int(pageinfo.max_page) if max_page != cur_page and t_max_page: cur_page = max_page pageinfo, coupons = paginator.paginate( coupons_data, cur_page, count_per_page, query_string=request.META['QUERY_STRING']) # 避免便利整个优惠券列表 member_ids = [c.member_id for c in coupons] members = get_member_by_id_list(member_ids) member_id2member = dict([(m.id, m) for m in members]) # 获取被使用的优惠券使用者信息 coupon_ids = [c.id for c in coupons if c.status == COUPON_STATUS_USED] orders = Order.get_orders_by_coupon_ids(coupon_ids) if orders: coupon_id2webapp_user_id = dict([(o.coupon_id, \ {'id': o.id, 'user': o.webapp_user_id, 'order_id': o.order_id, 'created_at': o.created_at}) \ for o in orders]) else: coupon_id2webapp_user_id = {} response = create_response(200) response.data.items = [] #统计是否有active的coupon # has_active_coupon = False now = datetime.today() for coupon in coupons: cur_coupon = JsonResponse() cur_coupon.id = coupon.id cur_coupon.coupon_id = coupon.coupon_id cur_coupon.provided_time = coupon.provided_time.strftime( "%Y-%m-%d %H:%M") cur_coupon.created_at = coupon.created_at.strftime( "%Y-%m-%d %H:%M") cur_coupon.money = str(coupon.money) cur_coupon.is_manual_generated = coupon.is_manual_generated cur_member = JsonResponse() member_id = int(coupon.member_id) # if coupon.status == COUPON_STATUS_UNUSED: # has_active_coupon = True if member_id in member_id2member: member = member_id2member[member_id] cur_member.username_truncated = member.username_truncated cur_member.username_for_html = member.username_for_html else: member = '' cur_member.username_truncated = '' cur_member.username_for_html = '' cur_member.id = member_id consumer = JsonResponse() consumer.username_truncated = '' consumer.username_for_html = '' if coupon.status == COUPON_STATUS_USED: if coupon.id in coupon_id2webapp_user_id: order = coupon_id2webapp_user_id[coupon.id] cur_coupon.order_id = order['id'] cur_coupon.order_fullid = order['order_id'] cur_coupon.use_time = order['created_at'].strftime( "%Y-%m-%d %H:%M") webapp_user_id = order['user'] member = WebAppUser.get_member_by_webapp_user_id( webapp_user_id) if member: consumer.username_truncated = member.username_truncated consumer.username_for_html = member.username_for_html consumer.id = member.id else: consumer.username_truncated = '未知' consumer.username_for_html = '未知' else: consumer.username_truncated = '未知' consumer.username_for_html = '未知' cur_coupon.status = COUPONSTATUS.get(coupon.status)['name'] elif coupon.expired_time <= now: cur_coupon.status = COUPONSTATUS.get( COUPON_STATUS_EXPIRED)['name'] else: cur_coupon.status = COUPONSTATUS.get(coupon.status)['name'] cur_coupon.member = cur_member cur_coupon.consumer = consumer cur_coupon.rule_name = id2rule[coupon.coupon_rule_id].name response.data.items.append(cur_coupon) response.data.sortAttr = request.GET.get('sort_attr', '-created_at') response.data.pageinfo = paginator.to_dict(pageinfo) return response.get_response()
def record_prize(request): member_id = request.GET.get('member_id', None) request_member = request.member response = create_response(200) error_msg = '' send_price = 0 play_count = 0 #try: # if member_id is None: # opid = request.GET.get('oid', None) # member_id = MemberHasSocialAccount.objects.filter(account__openid=opid)[0].member.id member = Member.objects.get(id=request_member.id) # except: # member = None # if member and member.id != request_member.id: # member = None if member and member.is_subscribed: detail_id = int(request.GET.get('shake_detail_id', 0)) if detail_id != 0: now = datetime.now() #try: now_join_count = ShakeRecord.objects.filter( shake_detail_id=detail_id).count() max_price_member = False if now_join_count >= 30: max_price_member = (0 == now_join_count % 30) with transaction.atomic(): shake_detail = ShakeDetail.objects.select_for_update().get( id=detail_id) member_play_count = ShakeRecord.objects.filter( member=member, shake_detail_id=detail_id).count() next_shake_details = ShakeDetail.objects.filter( shake=shake_detail.shake, start_at__gte=shake_detail.end_at).order_by('start_at') if next_shake_details.count() > 0: next_shake_detail = next_shake_details[0] else: next_shake_detail = None if shake_detail.shake.is_deleted == False and shake_detail.start_at <= now and shake_detail.end_at >= now: if shake_detail.residue_price > 10: if member_play_count >= shake_detail.play_count: if next_shake_detail: error_msg = u'本轮红包已抢光!' else: error_msg = u'红包已抢光,感谢您今天的参与!' else: if shake_detail.residue_price <= shake_detail.fixed_price or shake_detail.residue_price <= shake_detail.random_price_end: send_price = random.uniform( 1, float(shake_detail.residue_price)) elif max_price_member and shake_detail.fixed_price_residue_number > 0: # and shake_detail.residue_price > shake_detail.fixed_price: send_price = shake_detail.fixed_price max_price_member = False else: send_price = random.uniform( float(shake_detail.random_price_start), float(shake_detail.random_price_end)) max_price_member = False if send_price > 0 and send_price < shake_detail.residue_price: send_price = to_decimal(send_price, 2) shake_detail.residue_price -= send_price if max_price_member: shake_detail.fixed_price_residue_number -= 1 assert shake_detail.fixed_price_residue_number >= 0 shake_detail.save(update_fields=[ 'residue_price', 'fixed_price_residue_number' ]) else: shake_detail.save( update_fields=['residue_price']) record = ShakeRecord.objects.create( owner_id=request.webapp_owner_id, shake_detail=shake_detail, member=member, money=send_price) play_count = shake_detail.play_count - member_play_count - 1 try: ip = request.META['REMOTE_ADDR'] except: ip = None tasks.send_red_pack_task.delay( shake_detail.id, request.webapp_owner_id, member.id, record.id, ip) else: error_msg = shake_detail.shake.not_winning_desc else: if next_shake_detail: error_msg = u'本轮红包已抢光!' else: error_msg = u'红包已抢光,感谢您今天的参与!' else: error_msg = u'红包已抢光,感谢您今天的参与!' # except: # error_msg = u'活动不存在' else: error_msg = u"请先关注公众号" result = JsonResponse() result.error_msg = error_msg result.send_price = float(send_price) result.play_count = play_count response.data.result = result return response.get_response()
def edit_lottery_view(request, id): id = int(id) if id: lottery = Lottery.objects.get(id=id) lottery.can_update = False if lottery.status == LOTTERY_STATUS_NO_START: lottery.can_update = True relations = LotteryHasPrize.objects.filter(lottery=lottery) prize_ids = [r.prize_id for r in relations] prizes = Prize.objects.filter(id__in=prize_ids) id2prize = dict([(p.id, p) for p in prizes]) lottery.prizes = [] for r in relations: prize = id2prize[r.prize_id] prize.prize_source = r.prize_source prize.prize_type = r.prize_type lottery.prizes.append(prize) lottery.prizes.sort(lambda x,y: cmp(x.level, y.level)) #转换为json response = JsonResponse() response.id = lottery.id response.name = lottery.name response.detail = lottery.detail response.expend_integral = lottery.expend_integral response.can_repeat = lottery.can_repeat response.daily_play_count = lottery.daily_play_count response.type = lottery.type response.award_hour = lottery.award_hour response.not_win_desc = lottery.not_win_desc if lottery.award_type: response.award_type = lottery.award_type else: response.award_type = '' response.start_at = lottery.start_at.strftime("%Y-%m-%d") response.end_at = lottery.end_at.strftime("%Y-%m-%d") response.prizes = {} for prize in lottery.prizes: prize_json = {} prize_json['prize_source'] = prize.prize_source prize_json['prize_type'] = prize.prize_type prize_json['prize_name'] = prize.name prize_json['prize_level'] = prize.level prize_json['prize_odds'] = prize.odds prize_json['prize_count'] = prize.count response.prizes[prize.id] = prize_json lottery_json = response.get_json() else: lottery = {'can_update': True} lottery_json = '' coupon_rules = get_coupon_rules(request.user) c = RequestContext(request, { 'first_nav_name': MARKET_TOOLS_NAV, 'second_navs': export.get_second_navs(request), 'second_nav_name': SECOND_NAV_NAME, 'lottery': lottery, 'lottery_json':lottery_json, 'coupon_rules':coupon_rules }) return render_to_response('lottery/editor/edit_lottery.html', c)
def get_messages(request): response = JsonResponse() response.code = 200 response.data = JsonResponse() response.data.items = [] mpuser = get_system_user_binded_mpuser(request.user) if mpuser is None: return response.get_response() #获取当前页数 cur_page = int(request.GET.get('page', '1')) #获取每页个数 count = int(request.GET.get('count', COUNT_PER_PAGE)) is_debug = (request.GET.get('dbg', '0') == '1') is_collected = request.GET.get('is_collected', '') search_content = request.GET.get('search_content', '') if is_collected: collected_message_ids = CollectMessage.get_message_ids(request.user) ordering = 'FIELD(`id`, %s)' % ','.join( str(id) for id in collected_message_ids) messages = Message.objects.filter(id__in=collected_message_ids).extra( select={'ordering': ordering}, order_by=('ordering', )) elif search_content: data_before_tow_days = dateutil.get_previous_date('today', 2) messages = Message.objects.belong_to(request.user_profile.webapp_id, mpuser, search_content) else: messages = [] pageinfo, messages = paginate(messages, cur_page, count, query_string=request.META['QUERY_STRING']) webapp_id = request.user_profile.webapp_id for message in messages: weixin_user = message.session.weixin_user one_session = JsonResponse() one_session.id = message.id one_session.session_id = message.session.id one_session.sender_fake_id = weixin_user.fake_id one_session.sender_username = weixin_user.username one_session.sender_name = weixin_user.nickname_for_html if weixin_user.weixin_user_icon: one_session.weixin_user_icon = weixin_user.weixin_user_icon if len( weixin_user.weixin_user_icon.strip()) > 0 else DEFAULT_ICON else: one_session.weixin_user_icon = DEFAULT_ICON one_session.content = emotion.change_emotion_to_img(message.content) one_session.is_active = True if datetime.now( ) < message.created_at + timedelta( hours=EXPIRED_TIME) and datetime.now( ) > message.created_at else False if is_collected: one_session.is_active = False try: collect_message = CollectMessage.objects.get( message_id=message.id) one_session.created_at = __format_datetime( collect_message.created_at) except: one_session.created_at = __format_datetime(message.created_at) else: one_session.created_at = __format_datetime(message.created_at) one_session.message_id = message.id one_session.is_collected = CollectMessage.is_collected(message.id) one_session.message_type = message.message_type one_session.pic_url = message.pic_url one_session.audio_url = message.audio_url one_session.for_collected = is_collected one_session.hidden_a = True if message.message_type == IMAGE: one_session.content = message.pic_url if message.message_type == VOICE: one_session.content = message.audio_url one_session.is_subscribed = is_subscribed(weixin_user) try: account = SocialAccount.objects.get(webapp_id=webapp_id, openid=weixin_user.username) member = MemberHasSocialAccount.objects.filter( account=account)[0].member #member = session2member[session.weixin_user_id] if member: one_session.member_id = member.id one_session.member_remarks_name = member.remarks_name if member.user_icon and 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 response.data.items.append(one_session) response.data.page_info = __package_pageinfo(pageinfo) return response.get_response()
def get_sessions(request): response = JsonResponse() response.code = 200 response.data = JsonResponse() response.data.items = [] mpuser = get_system_user_binded_mpuser(request.user) if mpuser is None: return response.get_response() #获取当前页数 cur_page = int(request.GET.get('page', '1')) #获取每页个数 count = int(request.GET.get('count', COUNT_PER_PAGE)) is_debug = (request.GET.get('dbg', '0') == '1') #收藏记录 is_collected = request.GET.get('is_collected', '0') start_time = request.GET.get('start_time', '').strip() end_time = request.GET.get('end_time', '').strip() search_content = request.GET.get('search_content', '').strip() if is_debug: sessions = Session.objects.select_related().filter(mpuser=mpuser) else: sessions = Session.objects.select_related().filter(mpuser=mpuser, is_show=True) if start_time and end_time: start_time = '%s 0:0:0' % start_time end_time = '%s 23:59:59' % end_time sessions = sessions.filter(latest_contact_created_at__gte=start_time, latest_contact_created_at__lte=end_time) pageinfo, sessions = paginate(sessions, cur_page, count, query_string=request.META['QUERY_STRING']) #清空未读消息数量 RealTimeInfo.objects.filter(mpuser=mpuser).update(unread_count=0) webapp_id = request.user_profile.webapp_id 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]) # session2member = dict([(member_has_social_account.account.openid, member_has_social_account.member) for member_has_social_account \ # in MemberHasSocialAccount.objects.filter()]) for session in sessions: weixin_user = username2weixin_user[session.weixin_user_id] one_session = JsonResponse() one_session.id = session.id one_session.session_id = session.id one_session.sender_fake_id = weixin_user.fake_id one_session.sender_username = weixin_user.username one_session.sender_name = weixin_user.nickname_for_html if weixin_user.weixin_user_icon: one_session.weixin_user_icon = weixin_user.weixin_user_icon if len( weixin_user.weixin_user_icon.strip()) > 0 else DEFAULT_ICON else: one_session.weixin_user_icon = DEFAULT_ICON one_session.content = emotion.change_emotion_to_img( session.latest_contact_content) one_session.created_at = __format_datetime( session.latest_contact_created_at) one_session.unread_count = session.unread_count one_session.message_id = session.message_id one_session.is_collected = CollectMessage.is_collected( session.message_id) one_session.for_collected = False one_session.hidden_a = False try: if session.message_id != 0: message = Message.objects.get(id=session.message_id) one_session.message_type = message.message_type one_session.pic_url = message.pic_url one_session.audio_url = message.audio_url else: one_session.message_type = 'text' one_session.pic_url = '' one_session.audio_url = '' except: one_session.message_type = 'text' one_session.pic_url = '' one_session.audio_url = '' one_session.is_subscribed = is_subscribed(weixin_user) one_session.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: account = SocialAccount.objects.get(webapp_id=webapp_id, openid=weixin_user.username) member = MemberHasSocialAccount.objects.filter( account=account)[0].member #member = session2member[session.weixin_user_id] if member: one_session.member_id = member.id one_session.member_remarks_name = member.remarks_name if member.user_icon and 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:{}, webapp_id:{},cause:\n{}".format( session.weixin_user_id, webapp_id, unicode_full_stack()) watchdog_notice(notify_message) continue response.data.items.append(one_session) response.data.page_info = __package_pageinfo(pageinfo) return response.get_response()
def get_records(request): sort_attr = request.GET.get('sort_attr', '-created_at') point_cards = PointCard.objects.filter( owner=request.user).order_by(sort_attr) point_card_rule_id2point_card_rule = dict([ (rule.id, rule) for rule in PointCardRule.get_all_point_card_rules_list(request.user) ]) roles = [] for id in point_card_rule_id2point_card_rule: cur_point_card = JsonResponse() cur_point_card.name = point_card_rule_id2point_card_rule[id].name cur_point_card.id = point_card_rule_id2point_card_rule[id].id roles.append(cur_point_card) member_ids = [c.member_id for c in point_cards] members = get_member_by_id_list(member_ids) member_id2member = dict([(m.id, m) for m in members]) has_active_point_card = False #处理过滤 filter_attr = request.GET.get('filter_attr', None) filter_value = int(request.GET.get('filter_value', -1)) if filter_attr and (filter_value != -1): params = {filter_attr: filter_value} point_cards = point_cards.filter(**params) #进行分页 count_per_page = int(request.GET.get('count_per_page', 15)) cur_page = int(request.GET.get('page', '1')) pageinfo, point_cards = paginator.paginate( point_cards, cur_page, count_per_page, query_string=request.META['QUERY_STRING']) items = [] for point_card in point_cards: cur_point_card = JsonResponse() cur_point_card.id = point_card.id cur_point_card.point_card_rule_name = point_card_rule_id2point_card_rule[ point_card.point_card_rule_id].name if point_card.status == POINT_CARD_STATUS_UNUSED: has_active_point_card = True cur_member = JsonResponse() member_id = int(point_card.member_id) if member_id in member_id2member: member = member_id2member[member_id] cur_member.username_for_html = member.username_for_html else: member = '' cur_member.username_for_html = '' cur_point_card.member = cur_member cur_point_card.status = point_card.status cur_point_card.point_card_id = point_card.point_card_id cur_point_card.created_at = point_card.created_at.strftime("%Y-%m-%d") cur_point_card.password = point_card.password cur_point_card.point = int(point_card.point) items.append(cur_point_card) response = create_response(200) data = JsonResponse() data.items = items data.has_active_point_card = has_active_point_card data.sortAttr = request.GET.get('sort_attr', '-created_at') response.data = data response.data.pageinfo = paginator.to_dict(pageinfo) response.data.roles = roles return response.get_response()
def get_session_histories(request): session_id = request.GET['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() response = create_response(200) response.data.items = [] session = Session.objects.get(id=session_id) webapp_id = request.user_profile.webapp_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 response.data.is_active = is_active for message in 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.content = emotion.change_emotion_to_img(message.content) if one_message.content == None: one_message.content = '' one_message.weixin_created_at = __format_datetime( message.weixin_created_at) one_message.is_collected = CollectMessage.is_collected(message.id) one_message.message_type = message.message_type one_message.pic_url = message.pic_url one_message.audio_url = message.audio_url if message.message_type == IMAGE: one_message.content = message.pic_url if message.message_type == VOICE: one_message.content = message.audio_url if message.is_reply: one_message.sender_icon = mpuser_preview_info.image_path #sender.weixin_user_icon one_message.sender_name = mpuser_preview_info.name else: account = SocialAccount.objects.get(webapp_id=webapp_id, openid=sender.username) member = MemberHasSocialAccount.objects.filter( account=account)[0].member if member: if member.user_icon: one_message.sender_icon = member.user_icon if len( member.user_icon.strip()) > 0 else DEFAULT_ICON else: one_message.sender_icon = DEFAULT_ICON one_message.sender_name = member.username_for_html one_message.member_id = member.id if one_message.sender_icon != sender.weixin_user_icon: sender.weixin_user_icon = member.user_icon else: if sender.weixin_user_icon: 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 response.data.items.append(one_message) return response.get_response()
def get_channel_qrcode_settings(request): """ 获取渠道扫码配置列表 """ #处理搜索 query = request.GET.get('query', '').strip() if query: settings = ChannelQrcodeSettings.objects.filter(owner=request.user, name__contains=query) else: settings = ChannelQrcodeSettings.objects.filter(owner=request.user) setting_ids = [s.id for s in settings] relations = ChannelQrcodeHasMember.objects.filter( channel_qrcode_id__in=setting_ids) 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 = member_model.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 = mall_model.Order.by_webapp_user_id(webapp_user_ids).filter( status=mall_model.ORDER_STATUS_SUCCESSED) member_id2total_final_price = {} for order in orders: member_id = webapp_user_id2member_id[order.webapp_user_id] if member_id in member_id2total_final_price: member_id2total_final_price[member_id] += order.final_price else: member_id2total_final_price[member_id] = order.final_price setting_id2total_final_price = {} for member_id in member_id2total_final_price.keys(): final_price = member_id2total_final_price[member_id] setting_id = member_id2setting_id[member_id] if setting_id in setting_id2total_final_price: setting_id2total_final_price[setting_id] += final_price else: setting_id2total_final_price[setting_id] = final_price response = create_response(200) response.data.items = [] items = [] mp_user = get_binding_weixin_mpuser(request.user) mpuser_access_token = get_mpuser_accesstoken(mp_user) for setting in settings: cur_setting = JsonResponse() prize_info = decode_json_str(setting.award_prize_info) if prize_info['name'] == '_score-prize_': setting.cur_prize = '[%s]%d' % (prize_info['type'], prize_info['id']) elif prize_info['name'] == 'non-prize': setting.cur_prize = prize_info['type'] else: setting.cur_prize = '[%s]%s' % (prize_info['type'], prize_info['name']) if setting.id in setting_id2count: setting.count = setting_id2count[setting.id] else: setting.count = 0 if setting.id in setting_id2total_final_price: setting.total_final_price = setting_id2total_final_price[ setting.id] else: setting.total_final_price = 0 #如果没有ticket信息则获取ticket信息 if not setting.ticket: try: if mp_user.is_certified and mp_user.is_service and mpuser_access_token.is_active: weixin_api = get_weixin_api(mpuser_access_token) qrcode_ticket = weixin_api.create_qrcode_ticket( int(setting.id), QrcodeTicket.PERMANENT) try: ticket = qrcode_ticket.ticket except: ticket = '' setting.ticket = ticket setting.save() except: pass cur_setting.id = setting.id cur_setting.name = setting.name cur_setting.count = setting.count cur_setting.total_final_price = round(setting.total_final_price, 2) cur_setting.cur_prize = setting.cur_prize cur_setting.ticket = setting.ticket cur_setting.remark = setting.remark items.append(cur_setting) #进行分页 response.data.sortAttr = request.GET.get('sort_attr', 'count') if '-' in response.data.sortAttr: sorter = response.data.sortAttr[1:] is_reverse = True else: sorter = response.data.sortAttr is_reverse = False items = sorted(items, reverse=is_reverse, key=lambda b: getattr(b, sorter)) count_per_page = int(request.GET.get('count_per_page', 15)) cur_page = int(request.GET.get('page', '1')) pageinfo, items = paginator.paginate( items, cur_page, count_per_page, query_string=request.META['QUERY_STRING']) # response.data.items = items response.data.pageinfo = paginator.to_dict(pageinfo) return response.get_response()
def get_records(request): user = request.user.get_profile() records = ShakeRecord.objects.filter(owner=request.user).order_by('-created_at') #进行分页 count_per_page = int(request.GET.get('count_per_page', 15)) cur_page = int(request.GET.get('page', '1')) pageinfo, records = paginator.paginate(records, cur_page, count_per_page, query_string=request.META['QUERY_STRING']) response = create_response(200) response.data.items = [] for record in records: member = record.member one_record = JsonResponse() if member: one_record.username = member.username_for_html one_record.user_id = member.id else: one_record.username = u'未知' one_record.user_id = 0 one_record.money = str(record.money) one_record.name = record.shake_detail.shake.name one_record.is_sended = record.is_sended one_record.created_at = record.created_at.strftime('%Y-%m-%d %H:%M:%S') one_record.id = record.id response.data.items.append(one_record) response.data.pageinfo = paginator.to_dict(pageinfo) response.data.sortAttr = request.GET.get('sort_attr', '-created_at') return response.get_response()
def _get_channel_qrcode_items(request): #处理搜索 from mall.models import * query = request.GET.get('query', '').strip() sort_attr = request.GET.get('sort_attr', '-created_at') created_at = '-created_at' if 'created_at' in sort_attr: created_at = sort_attr setting = MemberChannelQrcodeSettings.objects.filter(owner=request.manager) if setting.count() > 0: member_channel_qrcodes = MemberChannelQrcode.objects.filter( member_channel_qrcode_setting=setting[0]) if query: member_ids = [ qrcode.member_id for qrcode in member_channel_qrcodes ] query_hex = byte_to_hex(query) members = member_model.Member.objects.filter( id__in=member_ids).filter(username_hexstr__contains=query_hex) member_ids = [m.id for m in members] member_channel_qrcodes = member_channel_qrcodes.filter( member_id__in=member_ids) else: return create_response(500).get_response() member_channel_qrcode_ids = [ qrcode.id for qrcode in member_channel_qrcodes ] relations = MemberChannelQrcodeHasMember.objects.filter( member_channel_qrcode__in=member_channel_qrcode_ids) member_channel_qrcode_id2count = {} member_id2member_channel_qrcode_id = {} member_id2relation = {} member_ids = [] for r in relations: member_ids.append(r.member_id) member_id2member_channel_qrcode_id[ r.member_id] = r.member_channel_qrcode_id member_id2relation[r.member_id] = r if r.member_channel_qrcode_id in member_channel_qrcode_id2count: member_channel_qrcode_id2count[r.member_channel_qrcode_id] += 1 else: member_channel_qrcode_id2count[r.member_channel_qrcode_id] = 1 webapp_users = member_model.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__in=(ORDER_STATUS_PAYED_SUCCESSED, ORDER_STATUS_PAYED_NOT_SHIP, ORDER_STATUS_PAYED_SHIPED, ORDER_STATUS_SUCCESSED)) member_id2total_final_price = {} member_id2cash_money = {} member_id2weizoom_card_money = {} for order in orders: member_id = webapp_user_id2member_id[order.webapp_user_id] if member_id2relation[member_id].is_new or member_id2relation[ member_id].created_at <= order.created_at: if member_id in member_id2total_final_price: member_id2total_final_price[ member_id] += order.final_price + order.weizoom_card_money member_id2cash_money[member_id] += order.final_price member_id2weizoom_card_money[ member_id] += order.weizoom_card_money else: member_id2total_final_price[ member_id] = order.final_price + order.weizoom_card_money member_id2cash_money[member_id] = order.final_price member_id2weizoom_card_money[ member_id] = order.weizoom_card_money member_channel_qrcode_id2total_final_price = {} member_channel_qrcode_id2cash_money = {} member_channel_qrcode_id2weizoom_card_money = {} for member_id in member_id2total_final_price.keys(): final_price = member_id2total_final_price[member_id] cash_money = member_id2cash_money[member_id] weizoom_card_money = member_id2weizoom_card_money[member_id] member_channel_qrcode_id = member_id2member_channel_qrcode_id[ member_id] if member_channel_qrcode_id in member_channel_qrcode_id2total_final_price: member_channel_qrcode_id2total_final_price[ member_channel_qrcode_id] += final_price member_channel_qrcode_id2cash_money[ member_channel_qrcode_id] += cash_money member_channel_qrcode_id2weizoom_card_money[ member_channel_qrcode_id] += weizoom_card_money else: member_channel_qrcode_id2total_final_price[ member_channel_qrcode_id] = final_price member_channel_qrcode_id2cash_money[ member_channel_qrcode_id] = cash_money member_channel_qrcode_id2weizoom_card_money[ member_channel_qrcode_id] = weizoom_card_money response = create_response(200) #response.data.items = [] items = [] mp_user = get_binding_weixin_mpuser(request.manager) mpuser_access_token = get_mpuser_accesstoken(mp_user) for qrcode in member_channel_qrcodes: current_qrcode = JsonResponse() if qrcode.id in member_channel_qrcode_id2count: qrcode.count = member_channel_qrcode_id2count[qrcode.id] else: qrcode.count = 0 if qrcode.id in member_channel_qrcode_id2total_final_price: qrcode.total_final_price = member_channel_qrcode_id2total_final_price[ qrcode.id] qrcode.cash_money = member_channel_qrcode_id2cash_money[qrcode.id] qrcode.weizoom_card_money = member_channel_qrcode_id2weizoom_card_money[ qrcode.id] else: qrcode.total_final_price = 0 qrcode.cash_money = 0 qrcode.weizoom_card_money = 0 #如果没有ticket信息则获取ticket信息 if not qrcode.ticket: try: if mp_user.is_certified and mp_user.is_service and mpuser_access_token.is_active: weixin_api = get_weixin_api(mpuser_access_token) qrcode_ticket = weixin_api.create_qrcode_ticket( int(qrcode.id), QrcodeTicket.PERMANENT) try: ticket = qrcode_ticket.ticket except: ticket = '' qrcode.ticket = ticket qrcode.save() except: pass current_qrcode.id = qrcode.id current_qrcode.name = qrcode.member.username_for_html current_qrcode.count = qrcode.count current_qrcode.total_final_price = round(qrcode.total_final_price, 2) current_qrcode.ticket = qrcode.ticket current_qrcode.created_at = qrcode.created_at.strftime( '%Y-%m-%d %H:%M:%S') items.append(current_qrcode) return items
def get_records(request): user = request.user.get_profile() red_envelopes = RedEnvelope.objects.filter(owner=request.user, is_deleted=False) red_envelope_ids = [r.id for r in red_envelopes] #处理搜索 query = request.GET.get('query', None) if query: query_hex = byte_to_hex(query) records = RedEnvelopeRecord.objects.filter( red_envelope_id__in=red_envelope_ids, prize_level__gt=0, prize_number=query_hex) else: records = RedEnvelopeRecord.objects.filter( red_envelope_id__in=red_envelope_ids, prize_level__gt=0) #进行分页 count_per_page = int(request.GET.get('count_per_page', 15)) cur_page = int(request.GET.get('page', '1')) pageinfo, records = paginator.paginate( records, cur_page, count_per_page, query_string=request.META['QUERY_STRING']) response = create_response(200) response.data.items = [] for record in records: member = WebAppUser.get_member_by_webapp_user_id(record.webapp_user_id) one_record = JsonResponse() if member: one_record.username = member.username_for_html one_record.user_id = member.id else: one_record.username = u'未知' one_record.user_id = 0 one_record.prize_number = record.prize_number one_record.red_envelope_name = record.red_envelope_name one_record.prize_money = str(record.prize_money) one_record.prize_name = record.prize_name one_record.prize_type = record.prize_type one_record.prize_detail = record.prize_detail one_record.created_at = record.created_at.strftime('%Y-%m-%d') one_record.awarded_at = record.awarded_at.strftime('%Y-%m-%d') one_record.is_awarded = record.is_awarded one_record.id = record.id response.data.items.append(one_record) response.data.pageinfo = paginator.to_dict(pageinfo) response.data.sortAttr = request.GET.get('sort_attr', '-created_at') return response.get_response()
def upload_richtexteditor_picture(request): uid = request.GET['uid'] request.user = User.objects.get(id=uid) if not request.user: raise RuntimeError('invalid user') title = request.POST['pictitle'] user_id = request.user.id file_name = request.POST['Filename'] #file_name = urllib.quote(file_name.encode('utf-8')).replace('%', '_').strip('_') file_name = __get_file_name(file_name) file = request.FILES.get('Filedata', None) content = [] if file: for chunk in file.chunks(): content.append(chunk) date = time.strftime('%Y%m%d') dir_path_suffix = '%d_%s' % (user_id, date) dir_path = os.path.join(settings.UPLOAD_DIR, dir_path_suffix) if not os.path.exists(dir_path): os.makedirs(dir_path) #file_name = '%s_%s' % (date, file_name) file_path = os.path.join(dir_path, file_name) dst_file = open(file_path, 'wb') print >> dst_file, ''.join(content) dst_file.close() url = '/static/upload/%s/%s' % (dir_path_suffix, file_name) if __validate_image(file_path): response = JsonResponse() response.url = url response.state = "SUCCESS" response.title = title return response.get_response() else: response = JsonResponse() response.state = "FAIL" response.title = title return response.get_response()