示例#1
0
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()
示例#2
0
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()
示例#3
0
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()
示例#4
0
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()
示例#5
0
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()
示例#6
0
def get_records(request):
    """
	获取中奖记录

	举例:http://weapp.weizoom.com/market_tools/lottery/api/records/get/?version=1&sort_attr=-created_at&count_per_page=15&page=1&enable_paginate=1&timestamp=1434434567924

	"""
    user = request.user.get_profile()
    lotteries = Lottery.objects.filter(owner=request.user, is_deleted=False)
    lottery_ids = [l.id for l in lotteries]

    #处理搜索
    query = request.GET.get('query', None)
    if query:
        query_hex = byte_to_hex(query)
        records = LotteryRecord.objects.filter(lottery_id__in=lottery_ids,
                                               prize_level__gt=0,
                                               prize_number=query_hex)
    else:
        records = LotteryRecord.objects.filter(lottery_id__in=lottery_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:
        one_record = JsonResponse()
        one_record.username = record.member.username_for_html
        one_record.user_id = record.member.id
        one_record.prize_number = record.prize_number
        one_record.prize_money = str(record.prize_money)
        one_record.lottery_name = record.lottery_name
        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()
示例#7
0
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()
示例#8
0
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()
示例#9
0
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)
示例#10
0
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()
示例#11
0
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()
示例#12
0
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()
示例#13
0
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
示例#14
0
文件: coupon.py 项目: chengdg/weizoom
    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()
示例#15
0
def get_cards(request):
    """
	卡规则列表 
	"""
    count_per_page = int(request.GET.get('count_per_page', '1'))
    cur_page = int(request.GET.get('page', '1'))
    card_name = request.GET.get('cardName', '').strip()
    weizoom_card_rule_id = int(request.GET.get('weizoom_card_rule_id', '-1'))
    weizoom_card_rules = WeizoomCardRule.objects.all().order_by('-created_at')
    weizoomcardpermission = WeiZoomCardPermission.objects.filter(
        user_id=request.user.id)
    can_export_batch_card = 0
    can_delay_card = 0
    if weizoomcardpermission:
        can_export_batch_card = weizoomcardpermission[0].can_export_batch_card
        can_delay_card = weizoomcardpermission[0].can_delay_card
    if card_name:
        weizoom_card_rules = weizoom_card_rules.filter(
            name__icontains=card_name)

    # 时间区间
    date_interval = request.GET.get('date_interval', '')
    if date_interval:
        date_interval = get_datetime_from_date_interval(date_interval)
        weizoom_card_rules = weizoom_card_rules.filter(
            valid_time_from__gte=date_interval[0],
            valid_time_to__lte=date_interval[1])

    filter_value = request.GET.get('filter_value', '')
    card_type = _get_type_value(filter_value)
    card_attr = _get_attr_value(filter_value)
    if card_type != -1:
        weizoom_card_rules = weizoom_card_rules.filter(card_type=card_type)
    if card_attr != -1:
        weizoom_card_rules = weizoom_card_rules.filter(card_attr=card_attr)

    #卡号区间查询
    card_num_min = request.GET.get('card_num_min', '')
    card_num_max = request.GET.get('card_num_max', '')

    if card_num_min or card_num_max:

        card_rule_ids = [int(r.id) for r in weizoom_card_rules]
        all_cards = WeizoomCard.objects.filter(
            weizoom_card_rule_id__in=card_rule_ids)
        rule_id2cards = {}

        for c in all_cards:
            card_rule_id = c.weizoom_card_rule_id
            if card_rule_id not in rule_id2cards:
                rule_id2cards[card_rule_id] = [c]
            else:
                rule_id2cards[card_rule_id].append(c)

        weizoom_card_id2rule_ids = {}

        for rule_id in rule_id2cards:
            for card in rule_id2cards[rule_id]:
                weizoom_card_id2rule_ids[card.weizoom_card_id] = rule_id

        card_num_set = set(int(i) for i in weizoom_card_id2rule_ids.keys())

        if card_num_min and card_num_max:
            max_num = int(card_num_max)
            min_num = int(card_num_min)
            search_set = set(range(min_num, max_num + 1))
        elif card_num_max:
            search_set = set([int(card_num_max)])
        elif card_num_min:
            search_set = set([int(card_num_min)])
        else:
            search_set = set([])
        result_set = search_set & card_num_set
        result_list = list(result_set)

        if len(result_list) > 0:
            filter_cards_id_list = []
            for card_num in result_list:
                filter_cards_id_list.append(u'%07d' % card_num)

            filter_rule_ids = []
            for card in filter_cards_id_list:
                r_id = weizoom_card_id2rule_ids[card]
                filter_rule_ids.append(r_id)
            filter_rule_ids = list(set(filter_rule_ids))
            weizoom_card_rules = weizoom_card_rules.filter(
                id__in=filter_rule_ids)
        if len(result_list) == 0:
            weizoom_card_rules = []

    pageinfo, weizoom_card_rules = paginator.paginate(
        weizoom_card_rules,
        cur_page,
        count_per_page,
        query_string=request.META['QUERY_STRING'])

    card_rule_ids = []
    user_ids = []
    for r in weizoom_card_rules:
        card_rule_ids.append(int(r.id))
        belong_to_owner_list = str(r.shop_limit_list).split(',')
        for a in belong_to_owner_list:
            if a != '-1':
                user_ids.append(a)
    user_id2store_name = {}
    user_profiles = UserProfile.objects.filter(user_id__in=user_ids)
    for user_profile in user_profiles:
        if user_profile.store_name:
            user_id2store_name[str(
                user_profile.user_id)] = user_profile.store_name

    all_cards = WeizoomCard.objects.filter(
        weizoom_card_rule_id__in=card_rule_ids)

    rule_id2card_ids = {}
    rule_id2cards = {}

    for c in all_cards:
        card_rule_id = c.weizoom_card_rule_id
        if card_rule_id not in rule_id2cards:
            rule_id2cards[card_rule_id] = [c]
        else:
            rule_id2cards[card_rule_id].append(c)

    for r_id in card_rule_ids:
        if r_id in rule_id2cards:
            weizoom_cards = rule_id2cards[r_id]
            weizoom_card_ids = [
                int(weizoom_cards[0].weizoom_card_id),
                int(weizoom_cards[::-1][0].weizoom_card_id)
            ]
            rule_id2card_ids[r_id] = weizoom_card_ids

    cur_weizoom_card_rules = []

    for rule in weizoom_card_rules:
        belong_to_owner_list2store_names = []
        belong_to_owner_list = str(rule.shop_limit_list).split(',')
        for a in belong_to_owner_list:
            if a != '-1':
                belong_to_owner_list2store_name = user_id2store_name.get(
                    a, None)
                belong_to_owner_list2store_names.append(
                    belong_to_owner_list2store_name)
        cur_weizoom_card_rule = JsonResponse()
        cur_weizoom_card_rule.id = rule.id
        cur_weizoom_card_rule.name = rule.name
        cur_weizoom_card_rule.count = rule.count
        cur_weizoom_card_rule.remark = rule.remark
        cur_weizoom_card_rule.money = '%.2f' % rule.money
        cur_weizoom_card_rule.card_type = rule.card_type
        cur_weizoom_card_rule.is_new_member_special = rule.is_new_member_special
        cur_weizoom_card_rule.card_attr = rule.card_attr
        cur_weizoom_card_rule.belong_to_owner = belong_to_owner_list2store_names
        cur_weizoom_card_rule.valid_time_from = rule.valid_time_from.strftime(
            '%Y-%m-%d %H:%M')
        cur_weizoom_card_rule.valid_time_to = rule.valid_time_to.strftime(
            '%Y-%m-%d %H:%M')
        cur_weizoom_card_rule.created_at = rule.created_at.strftime(
            '%Y-%m-%d %H:%M')
        #卡号区间
        try:
            weizoom_card_ids = rule_id2card_ids[cur_weizoom_card_rule.id]
            weizoom_card_id_start = weizoom_card_ids[0]
            weizoom_card_id_end = weizoom_card_ids[1]
            card_num_range = '%07d-%07d' % (weizoom_card_id_start,
                                            weizoom_card_id_end)
            cur_weizoom_card_rule.card_range = card_num_range
        except:
            pass

        # 卡类型
        if cur_weizoom_card_rule.card_type == WEIZOOM_CARD_EXTERNAL:
            cur_weizoom_card_rule.card_type = TYPE2NAME[
                'WEIZOOM_CARD_EXTERNAL']
        elif cur_weizoom_card_rule.card_type == WEIZOOM_CARD_INTERNAL:
            cur_weizoom_card_rule.card_type = TYPE2NAME[
                'WEIZOOM_CARD_INTERNAL']
        else:
            cur_weizoom_card_rule.card_type = TYPE2NAME['WEIZOOM_CARD_GIFT']
        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)
    response.data.can_delay_card = can_delay_card
    response.data.can_export_batch_card = can_export_batch_card
    return response.get_response()
示例#16
0
def list_messages(request):
    page = request.GET.get('page', 1)
    count = int(request.GET.get('count', 10))
    mpuser = get_system_user_binded_mpuser(request.user)
    isManager = request.GET.get('isManager', 'false')
    isSystemMenager = request.GET.get('isSystemMenager', 'false')
    if mpuser is None:
        response = create_response(500)
        response.errMsg = u'没有该用户的消息'
        return response.get_jsonp_response(request)

    sessions = Session.objects.select_related().filter(mpuser=mpuser,
                                                       is_show=True)

    #分页信息
    pageinfo, sessions = paginate(sessions,
                                  page,
                                  count,
                                  query_string=request.META['QUERY_STRING'])
    webapp_id = request.user_profile.webapp_id

    if isManager == "false" and isSystemMenager == "false":
        #清空未读消息数量
        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_json = []
    for session in sessions:
        weixin_user = username2weixin_user[session.weixin_user_id]
        content = session.latest_contact_content
        one_session = JsonResponse()
        one_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
        one_session.weixin_user_icon = weixin_user.weixin_user_icon if len(
            weixin_user.weixin_user_icon.strip()) > 0 else DEFAULT_ICON
        messages = Message.objects.filter(
            session=session.id).order_by('-created_at')
        message_st_type = messages[0].message_type
        if message_st_type == 'text':
            if len(content) > 10:
                content = content[0:10] + '...'
            elif len(content.strip()) <= 0:  #如果类型为text但是内容为空,则视为voice,有问题?
                content = '[语音]'
        elif message_st_type == 'image':
            content = '[图片]'
        elif message_st_type == 'voice':
            content = '[语音]'
        elif message_st_type == 'video':
            content = '[视频]'
        one_session.content = content
        one_session.created_at = __format_datetime(
            session.latest_contact_created_at)
        one_session.unread_count = session.unread_count
        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 = 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
            #raise
        sessions_list_json.append(one_session)
    response = create_response(200)
    response.data.iterms = sessions_list_json
    response.data.pressed_link = 'message'
    response.data.page_info = __package_pageinfo(pageinfo)
    return response.get_jsonp_response(request)