Ejemplo n.º 1
0
def total_statistics(request):
    total_statistics = dict()
    orders = Order.objects.all()
    order_count = orders.count()
    ship_count = 0
    for order in orders.filter(status=ORDER_STATUS_SUCCESSED):
        for order_has_product in OrderHasProduct.objects.filter(order=order):
            ship_count = ship_count + order_has_product.number

    order_successed = orders.filter(status=ORDER_STATUS_SUCCESSED).count()

    total_statistics['order_count'] = order_count
    total_statistics['ship_count'] = ship_count
    total_statistics['order_successed'] = order_successed
    total_price = 0
    for order in orders.filter(status=ORDER_STATUS_SUCCESSED):
        total_price = total_price + order.total_price
    total_statistics['total_price'] = total_price

    days = request.GET.get('days', None)
    date_statistics = dict()
    if days:
        total_days, low_date, cur_date, high_date = dateutil.get_date_range(
            dateutil.get_today(), days, 0)
        if low_date == high_date:
            date_orders = Order.objects.filter(
                created_at__year=low_date.year,
                created_at__month=low_date.month,
                created_at__day=low_date.day)

        else:
            if days.find('-') == -1:
                pass
            else:
                #total_days = total_days + 1
                high_date = high_date + timedelta(days=1)
            date_orders = Order.objects.filter(created_at__range=(low_date,
                                                                  high_date))

        ship_count = 0
        total_price = 0
        for order in date_orders.filter(
                status__gte=ORDER_STATUS_PAYED_SUCCESSED):
            for order_has_product in OrderHasProduct.objects.filter(
                    order=order):
                ship_count = ship_count + order_has_product.number
            total_price = total_price + order.total_price

        date_statistics = dict()
        date_statistics['order_count'] = date_orders.count()
        date_statistics['ship_count'] = ship_count
        #total_price = order.total_price
        date_statistics['total_price'] = total_price

    response = create_response(200)
    response.data.total_statistics = total_statistics
    response.data.date_statistics = date_statistics

    return response.get_response()
Ejemplo n.º 2
0
def get_visit_daily_trend(request):
    webapp_id = request.user_profile.webapp_id

    #先对昨天的数据进行统计
    #_count_visit_yestoday_daily_pv_uv(webapp_id)
    #对当天的统计结果进行更新
    _update_visit_today_daily_statistics(webapp_id)

    days = request.GET['days']

    total_days, low_date, cur_date, high_date = dateutil.get_date_range(
        dateutil.get_today(), days, 0)
    statisticses = PageVisitDailyStatistics.objects.filter(
        webapp_id=webapp_id,
        url_type=URL_TYPE_ALL,
        data_date__range=(low_date, high_date))

    date2pv = dict([(s.data_date.strftime('%Y-%m-%d'), s.pv_count)
                    for s in statisticses])
    date2uv = dict([(s.data_date.strftime('%Y-%m-%d'), s.uv_count)
                    for s in statisticses])

    date_list = dateutil.get_date_range_list(low_date, high_date)

    pv_trend_values = []
    uv_trend_values = []
    for loop_date in date_list:
        date = loop_date.strftime('%Y-%m-%d')
        x = (loop_date - low_date).days

        pv_trend_values.append({'x': x, 'y': date2pv.get(date, 0)})
        uv_trend_values.append({'x': x, 'y': date2uv.get(date, 0)})

    if len(pv_trend_values) == 0:
        values = []
    else:
        values = [{
            'title': u'PV数',
            'values': pv_trend_values
        }, {
            'title': u'UV数',
            'values': uv_trend_values
        }]

    infos = {
        'title': '',
        'values': values,
        'date_info': {
            'days': total_days,
            'low_date': low_date
        }
    }

    line_chart_json = chartutil.create_line_chart(
        infos, display_today_data=settings.IS_UPDATE_PV_UV_REALTIME)

    return HttpResponse(line_chart_json, 'application/json')
Ejemplo n.º 3
0
def get_card_channel_details(request):
    """
    微众卡明细页面
    """
    owner_id = request.GET.get('owner_id', '')
    start_date = request.GET.get('start_date', '')
    end_date = request.GET.get('end_date', '')
    channel = User.objects.get(id=owner_id)
    if not start_date:
        total_days, start_date, cur_date, end_date = dateutil.get_date_range(
            dateutil.get_today(), "6", 0)
        start_date = str(start_date) + ' 00:00:00'
        end_date = str(end_date) + ' 23:59:59'
    webapp = WebApp.objects.get(owner_id=owner_id)
    orders = Order.by_webapp_id(
        webapp.appid).filter(created_at__gte=start_date,
                             created_at__lte=end_date).order_by('-created_at')
    id2order_ids = {}
    for r in orders:
        id2order_ids[r.order_id] = r.id
    order_ids = id2order_ids.keys()
    card_orders = WeizoomCardHasOrder.objects.filter(
        order_id__in=order_ids).order_by('-created_at')
    # orders = WeizoomCardHasOrder.objects.filter(owner_id=owner_id,created_at__gte=start_date,created_at__lte=end_date).exclude(order_id=-1)
    use_money = 0
    refund = 0
    card_ids = set()
    order_ids = set()
    for order in card_orders:
        if order.event_type == "使用":
            use_money += order.money
        else:
            refund += order.money
        card_ids.add(order.card_id)
        order_ids.add(order.order_id)
    channel.use_money = '%.2f' % use_money
    channel.refund = '%.2f' % -refund
    channel.order_count = len(order_ids)
    channel.use_count = len(card_ids)
    channel.start_date = start_date
    channel.end_date = end_date

    c = RequestContext(
        request, {
            'first_nav_name': export.MALL_CARD_FIRST_NAV,
            'second_navs': export.get_card_second_navs(request),
            'second_nav_name': export.MALL_CARD_CENSUS_NAV,
            'third_nav_name': export.MALL_CARD_BY_CHANNEL_NAV,
            'channel': channel,
            'has_order': orders.count() > 0,
            'owner_id': owner_id
        })
    return render_to_response('card/editor/weizoom_channel_card_detail.html',
                              c)
Ejemplo n.º 4
0
def __get_weather_info(city_code, weather_id=0):
    data_str, error_info = __get_http_response_data(
        "m.weather.com.cn", "/data/%s.html" % city_code)
    weather_info = []
    weather = None
    if data_str:
        info_json = decode_json_str(data_str)
        weather_json = info_json['weatherinfo']

        # 计算周几
        weeks = [u'一', u'二', u'三', u'四', u'五', u'六', u'日']
        week_index = __get_week_index(weeks, weather_json['week'])

        # 获取今天日期
        today_date = datetime.now()
        total_days, low_date, cur_date, high_date = dateutil.get_date_range(
            dateutil.get_today(), '6', 6)
        date_list = dateutil.get_date_range_list(datetime.date(today_date),
                                                 high_date)

        for i in range(1, 7):
            data = dict()
            data['date'] = date_list[i - 1].strftime("%Y年%m月%d日")
            data['weather'] = weather_json['weather%d' % i]
            data['temp'] = weather_json['temp%d' % i]
            data['week'] = u'周%s' % weeks[week_index]
            # 给week赋值下标
            week_index = week_index + 1 if week_index + 1 < len(weeks) else 0
            weather_info.append(data)

        # 判断是否已经添加过数据,如果添加过就修改
        if weather_id:
            weather = Weather.objects.get(id=weather_id)
            weather.info = json.dumps(weather_info)
            weather.update_time = today_date
            weather.save()
        else:
            weather = Weather.objects.create(info=json.dumps(weather_info),
                                             city_code=city_code)
    else:
        if weather_id:
            weather = Weather.objects.get(id=weather_id)
            weather_info = json.loads(weather.info)
            # print u'更新数据,天气的api不可用!'
            watchdog_fatal(u'更新数据,天气的api不可用!%s' % error_info, WATCHDOG_TYPE)
        else:
            # print u'首次获取数据,天气的api不可用!'
            watchdog_fatal(u'首次获取数据,天气的api不可用!%s' % error_info, WATCHDOG_TYPE)
    return weather_info, weather
Ejemplo n.º 5
0
def get_chan_channel_census(request):
    """
    微众卡列表页面
    """
    total_days, start_date, cur_date, end_date = dateutil.get_date_range(
        dateutil.get_today(), "6", 0)
    start_date = str(start_date)
    end_date = str(end_date)
    has_cards = (WeizoomCard.objects.filter().count() > 0)
    c = RequestContext(
        request, {
            'first_nav_name': export.MALL_CARD_FIRST_NAV,
            'second_navs': export.get_card_second_navs(request),
            'second_nav_name': export.MALL_CARD_CENSUS_NAV,
            'third_nav_name': export.MALL_CARD_BY_CHANNEL_NAV,
            'has_cards': has_cards,
            'start_date': start_date,
            'end_date': end_date
        })
    return render_to_response('card/editor/list_weizoom_channel_card.html', c)
Ejemplo n.º 6
0
def get_new_weixin_user_daily_trend(request):
    webapp_id = request.user_profile.webapp_id

    days = request.GET['days']
    total_days, low_date, cur_date, high_date = dateutil.get_date_range(
        dateutil.get_today(), days, 0)
    statisticses = WeixinUserDailyStatistics.objects.filter(
        webapp_id=webapp_id, data_date__range=(low_date, high_date))

    date2count = dict([(s.data_date, s.count) for s in statisticses])
    date_list = dateutil.get_date_range_list(low_date, high_date)

    trend_values = []
    for loop_date in date_list:
        count = 0
        if loop_date in date2count:
            count = date2count[loop_date]

        x = (loop_date - low_date).days
        dot = {'x': x, 'y': count}
        trend_values.append(dot)

    if len(trend_values) == 0:
        values = []
    else:
        values = [{'title': '新增用户数', 'values': trend_values}]

    infos = {
        'title': '',
        'values': values,
        'date_info': {
            'days': total_days,
            'low_date': low_date
        }
    }

    line_chart_json = chartutil.create_line_chart(infos,
                                                  display_today_data=True)

    return HttpResponse(line_chart_json, 'application/json')
Ejemplo n.º 7
0
def get_message_daily_trend(request):
    days = request.GET['days']
    total_days, low_date, cur_date, high_date = dateutil.get_date_range(
        dateutil.get_today(), days, 0)
    statisticses = MessageDailyStatistics.objects.filter(
        owner=request.user, data_date__range=(low_date, high_date))

    date2count = dict([(s.data_date, s.count) for s in statisticses])
    date_list = dateutil.get_date_range_list(low_date, high_date)

    trend_values = []
    for loop_date in date_list:
        count = 0
        if loop_date in date2count:
            count = date2count[loop_date]

        x = (loop_date - low_date).days
        dot = {'x': x, 'y': count}
        trend_values.append(dot)

    if len(trend_values) == 0:
        values = []
    else:
        values = [{'title': '消息数', 'values': trend_values}]

    infos = {
        'title': '',
        'values': values,
        'date_info': {
            'days': total_days,
            'low_date': low_date
        }
    }

    line_chart_json = chartutil.create_line_chart(
        infos, display_today_data=settings.IS_UPDATE_PV_UV_REALTIME)

    return HttpResponse(line_chart_json, 'application/json')
Ejemplo n.º 8
0
    def api_get(request):
        """
		关键词分析
		"""
        #获取当前页数
        cur_page = int(request.GET.get('page', '1'))
        #获取每页个数
        count_per_page = int(request.GET.get('count_per_page', 10))

        days = request.GET.get('days', '7')
        keyword = request.GET.get('keyword', '')

        owner_id = request.manager.id
        total_days, low_date, cur_date, high_date = dateutil.get_date_range(
            dateutil.get_today(), days, 0)
        date_list = [
            date.strftime("%Y-%m-%d")
            for date in dateutil.get_date_range_list(low_date, high_date)
        ]
        display_date_list = [
            date.strftime("%m.%d")
            for date in dateutil.get_date_range_list(low_date, high_date)
        ]

        records = KeywordCount.objects.filter(
            owner_id=owner_id,
            date__range=(low_date, high_date),
            keyword__contains=keyword).annotate(
                total_count=Sum('count')).order_by('-total_count')
        new_records = {}

        for record in records:
            new_record = {}
            count = record.count
            if new_records.has_key(record.keyword):
                count += new_records[record.keyword]
            new_records[record.keyword] = count

        new_records = sorted(new_records.items(),
                             key=lambda d: d[1],
                             reverse=True)

        pageinfo, new_records = paginator.paginate(new_records, cur_page,
                                                   count_per_page, None)

        items = []
        num = 1  #计算排行id使用
        for record in new_records:
            record_item = {}
            record_item['id'] = (cur_page - 1) * count_per_page + num
            num += 1
            record_item['keyword'] = record[0]
            record_item['count'] = record[1]

            items.append(record_item)

        response = create_response(200)
        response.data = {
            'items': items,
            'pageinfo': paginator.to_dict(pageinfo),
            'sortAttr': ''
        }

        return response.get_response()
Ejemplo n.º 9
0
    def api_get(request):
        """
		页面访问
		"""
        days = request.GET.get('days', 7)
        try:
            owner_id = request.manager.id
            total_days, low_date, cur_date, high_date = dateutil.get_date_range(
                dateutil.get_today(), days, 0)
            date_list = [
                date.strftime("%Y-%m-%d")
                for date in dateutil.get_date_range_list(low_date, high_date)
            ]
            display_date_list = [
                date.strftime("%m.%d")
                for date in dateutil.get_date_range_list(low_date, high_date)
            ]

            analysis = MessageAnalysis.objects.filter(
                owner_id=owner_id,
                date_time__range=(low_date,
                                  (high_date +
                                   timedelta(days=1)))).order_by('date_time')

            date2receive = dict()
            date2send = dict()
            date2interaction_user = dict()
            date2interaction = dict()

            for analys in analysis:
                date = analys.date_time.strftime("%Y-%m-%d")
                date2receive[date] = analys.receive_count
                date2send[date] = analys.send_count
                date2interaction_user[date] = analys.interaction_user_count
                date2interaction[date] = analys.interaction_count

            receive_count_values = []
            send_count_values = []
            interaction_user_count_values = []
            interaction_count_values = []
            for date in date_list:
                receive_count_values.append(date2receive.get(date, 0))
                send_count_values.append(date2send.get(date, 0))
                interaction_user_count_values.append(
                    date2interaction_user.get(date, 0))
                interaction_count_values.append(date2interaction.get(date, 0))

            return create_line_chart_response(
                '', '', display_date_list,
                [{
                    "name": "接收消息数",
                    "values": receive_count_values
                }, {
                    "name": "发送消息数",
                    "values": send_count_values
                }, {
                    "name": "互动人数",
                    "values": interaction_user_count_values
                }, {
                    "name": "互动次数",
                    "values": interaction_count_values
                }], ["#11ca64", "#ca117e", "#00a2ff", "#ff9600"])
        except:
            if settings.DEBUG:
                raise
            else:
                response = create_response(500)
                response.innerErrMsg = unicode_full_stack()
                return response.get_response()
Ejemplo n.º 10
0
    def api_get(request):
        """
		用户分析
		"""
        days = request.GET.get('days', 7)
        try:
            owner_id = request.manager.id
            total_days, low_date, cur_date, high_date = dateutil.get_date_range(
                dateutil.get_today(), days, 0)
            date_list = [
                date.strftime("%Y-%m-%d")
                for date in dateutil.get_date_range_list(low_date, high_date)
            ]
            display_date_list = [
                date.strftime("%m.%d")
                for date in dateutil.get_date_range_list(low_date, high_date)
            ]

            analysis = MemberAnalysis.objects.filter(
                owner_id=owner_id,
                date_time__range=(low_date,
                                  (high_date +
                                   timedelta(days=1)))).order_by('date_time')

            date2added = dict()
            date2cancel = dict()
            date2net = dict()
            date2total = dict()

            for analys in analysis:
                date = analys.date_time
                date2added[date] = analys.new_user
                date2cancel[date] = analys.cancel_user
                date2net[date] = analys.net_growth
                date2total[date] = analys.cumulate_user

            added_trend_values = []
            cancel_trend_values = []
            net_trend_values = []
            total_trend_values = []
            for date in date_list:
                added_trend_values.append(date2added.get(date, 0))
                cancel_trend_values.append(date2cancel.get(date, 0))
                net_trend_values.append(date2net.get(date, 0))
                total_trend_values.append(date2total.get(date, 0))

            return create_line_chart_response(
                '', '', display_date_list, [{
                    "name": "新增人数",
                    "values": added_trend_values
                }, {
                    "name": "跑路人数",
                    "values": cancel_trend_values
                }, {
                    "name": "净增人数",
                    "values": net_trend_values
                }, {
                    "name": "累计人数",
                    "values": total_trend_values
                }], ["#11ca64", "#e2bf91", "#ca117e", "#00a2ff"])
        except:
            if settings.DEBUG:
                raise
            else:
                response = create_response(500)
                response.innerErrMsg = unicode_full_stack()
                return response.get_response()
Ejemplo n.º 11
0
    def api_get(request):
        webapp_id = request.user_profile.webapp_id
        if request.GET.get('get_outline_data', None):
            # 获得昨日订单数据
            today = '%s 23:59:59' % dateutil.get_yesterday_str('today')
            yesterday = '%s 00:00:00' % dateutil.get_yesterday_str('today')
            order_money, order_count = stats_util.get_transaction_money_order_count(
                webapp_id, yesterday, today)

            # 获取会员数 update by bert at 20150817
            subscribed_member_count = member_models.Member.objects.filter(
                webapp_id=webapp_id, is_subscribed=True,
                is_for_test=False).count()
            new_member_count = member_models.Member.objects.filter(
                webapp_id=webapp_id,
                created_at__range=(yesterday, today),
                status=member_models.SUBSCRIBED,
                is_for_test=False).count()

            response = create_response(200)
            response.data = {
                'unread_message_count':
                get_unread_message_count(request.manager),
                'new_member_count': new_member_count,
                'order_count': order_count,
                'order_money': round(order_money, 2),
                'subscribed_member_count': subscribed_member_count,
                'shop_hint_data': _get_shop_hint_data(request),
                'tomorrow': dateutil.get_tomorrow_str('today')
            }

            return response.get_response()
        else:
            type = request.GET.get('type', None)
            days = request.GET.get('days', 6)
            total_days, low_date, cur_date, high_date = dateutil.get_date_range(
                dateutil.get_today(), days, 0)
            # high_date -= timedelta(days=1)
            date_list = [
                date.strftime("%Y-%m-%d")
                for date in dateutil.get_date_range_list(low_date, high_date)
            ]
            #当最后一天是今天时,折线图中不显示最后一天的数据 duhao 2015-09-17
            #当起止日期都是今天时,数据正常显示
            today = dateutil.get_today()
            if len(date_list) > 1 and date_list[-1] == today:
                del date_list[-1]

            if type and type == 'purchase_trend':
                try:
                    date2count = dict()
                    date2price = dict()

                    # 11.20从查询mall_purchase_daily_statistics变更为直接统计订单表,解决mall_purchase_daily_statistics遗漏统计订单与统计时间不一样导致的统计结果不同的问题。
                    orders = mall_models.Order.objects.belong_to(
                        webapp_id).filter(
                            created_at__range=(low_date, (high_date) +
                                               timedelta(days=1)))
                    statuses = set([
                        mall_models.ORDER_STATUS_PAYED_SUCCESSED,
                        mall_models.ORDER_STATUS_PAYED_NOT_SHIP,
                        mall_models.ORDER_STATUS_PAYED_SHIPED,
                        mall_models.ORDER_STATUS_SUCCESSED
                    ])
                    orders = [
                        order for order in orders
                        if (order.type != 'test') and (
                            order.status in statuses)
                    ]
                    for order in orders:
                        # date = dateutil.normalize_date(order.created_at)
                        date = order.created_at.strftime("%Y-%m-%d")
                        if order.webapp_id != webapp_id:
                            order_price = mall_models.Order.get_order_has_price_number(
                                order) + order.postage
                        else:
                            order_price = order.final_price + order.weizoom_card_money

                        if date in date2count:
                            old_count = date2count[date]
                            date2count[date] = old_count + 1
                        else:
                            date2count[date] = 1

                        if date in date2price:
                            old_price = date2price[date]
                            date2price[date] = old_price + order_price
                        else:
                            date2price[date] = order_price

                    count_trend_values = []
                    price_trend_values = []
                    for date in date_list:
                        count_trend_values.append(date2count.get(date, 0))
                        price_trend_values.append(
                            round(date2price.get(date, 0.0), 2))
                    result = create_line_chart_response(
                        '',
                        '',
                        date_list, [{
                            "name": "销售额",
                            "values": price_trend_values
                        }, {
                            "name": "订单数",
                            "values": count_trend_values
                        }],
                        use_double_y_lable=True,
                        get_json=True)
                    result['yAxis'][0]['name'] = '销售额'
                    result['yAxis'][1]['name'] = '订单数'
                    result['yAxis'][1]['splitLine'] = {'show': False}
                    response = create_response(200)
                    response.data = result
                    return response.get_response()
                except:
                    if settings.DEBUG:
                        raise
                    else:
                        response = create_response(500)
                        response.innerErrMsg = unicode_full_stack()
                        return response.get_response()
            elif type and type == 'visit_daily_trend':
                # 已弃用
                """
                获得每日pv、uv统计
                """

                # 对当天的统计结果进行更新
                if settings.IS_UPDATE_PV_UV_REALTIME:
                    # 先删除当天的pv,uv统计结果,然后重新进行统计
                    today = dateutil.get_today()
                    webapp_models.PageVisitDailyStatistics.objects.filter(
                        webapp_id=webapp_id, data_date=today).delete()
                    webapp_statistics_util.count_visit_daily_pv_uv(
                        webapp_id, today)

                statisticses = webapp_models.PageVisitDailyStatistics.objects.filter(
                    webapp_id=webapp_id,
                    url_type=webapp_models.URL_TYPE_ALL,
                    data_date__range=(low_date, high_date))

                date2pv = dict([(s.data_date.strftime('%Y-%m-%d'), s.pv_count)
                                for s in statisticses])
                date2uv = dict([(s.data_date.strftime('%Y-%m-%d'), s.uv_count)
                                for s in statisticses])

                pv_trend_values = []
                uv_trend_values = []
                for date in date_list:
                    pv_trend_values.append(date2pv.get(date, 0))
                    uv_trend_values.append(date2uv.get(date, 0))

                return create_line_chart_response('', '', date_list,
                                                  [{
                                                      "name": "PV",
                                                      "values": pv_trend_values
                                                  }, {
                                                      "name": "UV",
                                                      "values": uv_trend_values
                                                  }])
Ejemplo n.º 12
0
def get_order_daily_trend(request):
    days = request.GET['days']
    type = int(request.GET['type'])  # 1为柱状图,2为k线图

    elements = request.GET.get('element', '')
    if elements:
        elements = elements.split(',')

    total_days, low_date, cur_date, high_date = dateutil.get_date_range(
        dateutil.get_today(), days, 0)
    date_list = dateutil.get_date_range_list(low_date, high_date)

    if low_date == high_date:
        orders = Order.objects.filter(created_at__year=low_date.year,
                                      created_at__month=low_date.month,
                                      created_at__day=low_date.day)
    else:
        if days.find('-') == -1:
            date_list = date_list[:len(date_list) - 1]
        else:
            total_days = total_days + 1
            high_date = high_date + timedelta(days=1)
        orders = Order.objects.filter(created_at__range=(low_date, high_date))

    date2count = dict([(o, o) for o in range(1, 7)])

    trend_ordered_quantity_values = []
    trend_shiped_quantity_values = []
    trend_order_weixin_values = []
    trend_order_shopex_values = []
    trend_listened_record_values = []
    trend_recorded_values = []
    x_labels = []

    max_value = MAX_VALUE
    for loop_date in date_list:
        x = (loop_date - low_date).days
        x_labels.append(str(x))
        for e in elements:
            orders_filter_by_date = orders.filter(
                created_at__year=loop_date.year,
                created_at__month=loop_date.month,
                created_at__day=loop_date.day)
            e = int(e)
            if ORDERED_QUANTITY == e:
                count = orders_filter_by_date.count()
                dot = {'x': x, 'y': count}
                max_value = __get_max_values(count, max_value)
                trend_ordered_quantity_values.append(dot)

            if ORDERED_SHIPED_QUANTITY == e:
                count = 0
                for order in orders_filter_by_date.filter(
                        status__gte=ORDER_STATUS_PAYED_SUCCESSED):
                    for order_has_product in OrderHasProduct.objects.filter(
                            order=order):
                        count = count + order_has_product.number
                dot = {'x': x, 'y': count}
                max_value = __get_max_values(count, max_value)
                trend_shiped_quantity_values.append(dot)

            if ORDERED_TOTAL_PRICE == e:
                total_price = 0
                for order in orders_filter_by_date.filter(
                        status__gte=ORDER_STATUS_PAYED_SUCCESSED):
                    total_price = total_price + order.total_price
                dot = {'x': x, 'y': total_price}

                max_value = __get_max_values(total_price, max_value)
                trend_order_shopex_values.append(dot)

    values = []
    for e in elements:
        e = int(e)
        if ORDERED_QUANTITY == e:

            values.append({
                'title': u'日订单量',
                'values': trend_ordered_quantity_values
            })

        if ORDERED_SHIPED_QUANTITY == e:
            values.append({
                'title': u'日出货量',
                'values': trend_shiped_quantity_values
            })

        if ORDERED_TOTAL_PRICE == e:
            values.append({
                'title': u'日总金额',
                'values': trend_order_shopex_values
            })

    if type == 1:

        infos = {
            'title': '',
            'x_labels': x_labels,
            'bar_title': 'ttt',
            'x_legend_text': u'日期',
            'values': values,
            'max_value': max_value,
            'date_info': {
                'days': total_days,
                'low_date': low_date
            }
        }
        chart_json = chartutil.create_bar_chart(infos)
    else:
        infos = {
            'title': '',
            'values': values,
            'date_info': {
                'days': total_days,
                'low_date': low_date
            },
            'max_value': max_value
        }
        chart_json = chartutil.create_wine_line_chart(infos,
                                                      display_today_data=False)

    return HttpResponse(chart_json, 'application/json')
Ejemplo n.º 13
0
    def api_get(request):
        """
		签到详情查看
		"""
        member_id = request.GET.get('member_id', None)
        belong_to = request.GET.get('belong_to', None)
        if member_id and belong_to:
            #最近90天
            total_days, low_date, cur_date, high_date = dateutil.get_date_range(
                dateutil.get_today(), str(89), 0)
            date_list = dateutil.get_date_range_list(low_date, cur_date)

            #进行分页
            count_per_page = int(
                request.GET.get('count_per_page', COUNT_PER_PAGE))
            cur_page = int(request.GET.get('page', '1'))
            date_list.reverse()
            pageinfo, date_list = paginator.paginate(
                date_list,
                cur_page,
                count_per_page,
                query_string=request.META['QUERY_STRING'])
            pageinfo = paginator.to_dict(pageinfo)

            start_date = low_date.strftime("%Y-%m-%d %H:%M:%S")
            #现在的时间
            end_date = cur_date.strftime("%Y-%m-%d 23:59:59")

            items = app_models.exSignDetails.objects(
                belong_to=belong_to,
                member_id=int(member_id),
                created_at__gte=start_date,
                created_at__lte=end_date).order_by('-created_at')

            sign_member_ids = [item.member_id for item in items]
            member_id2info = {
                m.id: {
                    'is_subscribed': m.is_subscribed,
                    'member_name': m.username_for_html
                }
                for m in Member.objects.filter(id__in=sign_member_ids)
            }
            returnDataList = []
            time2prize = {}
            coupon_ids = []
            for t in items:
                if t['prize'].get('coupon', None):
                    coupon = t['prize']['coupon']
                    for c in coupon:
                        coupon_ids.append(c['id'])
            coupon_id2name = {
                c.id: c.name
                for c in promotion_models.CouponRule.objects.filter(
                    id__in=coupon_ids)
            }

            for item in items:
                prize_str = u''
                if item['prize'].get('integral', None):
                    prize_str += u'积分+%s<br/>' % str(item['prize']['integral'])
                if item['prize'].get('coupon', None):
                    coupon = item['prize']['coupon']
                    for c in coupon:
                        prize_str += u'%s<br/>' % coupon_id2name.get(
                            c['id'], '')
                time2prize[item.created_at.strftime("%Y.%m.%d")] = {
                    "created_at":
                    item.created_at.strftime("%Y.%m.%d %H:%M:%S"),
                    "created_at_f":
                    item.created_at.strftime("%Y-%m-%d %H:%M:%S"),
                    "prize": prize_str,
                    "status": 1
                }
            for date_d in date_list:
                date_ymd = date_d.strftime("%Y.%m.%d")
                if time2prize.get(date_ymd, None):
                    returnDataList.append(time2prize[date_ymd])
                else:
                    returnDataList.append({
                        "created_at":
                        date_d.strftime("%Y.%m.%d %H:%M:%S"),
                        "created_at_f":
                        date_d.strftime("%Y-%m-%d %H:%M:%S"),
                        "prize":
                        "",
                        "status":
                        0
                    })
        else:
            returnDataList = []
            pageinfo = None
        response = create_response(200)
        response.data.items = returnDataList
        response.data.pageinfo = pageinfo
        return response.get_response()
Ejemplo n.º 14
0
def get_channel_cards(sort_attr,
                      filter_value,
                      cur_page=None,
                      count_per_page=None,
                      query_string=""):
    orders_relation2card = WeizoomCardHasOrder.objects.exclude(
        order_id__in=['-1', '-2'])
    #处理过滤
    filter_data_args = {}
    filter_data_dict = {}
    start_date = end_date = ''
    if filter_value:
        for filter_data_item in filter_value.split('|'):
            try:
                key, value = filter_data_item.split(":")
            except:
                key = filter_data_item[:filter_data_item.find(':')]
                value = filter_data_item[filter_data_item.find(':') + 1:]
            filter_data_dict[key] = value

        if filter_data_dict.has_key('created_at'):
            value = filter_data_dict['created_at']
            if value.find('--') > -1:
                val1, val2 = value.split('--')
                start_date = val1 + ' 00:00:00'
                end_date = val2 + ' 23:59:59'
                orders = Order.objects.filter(created_at__gte=start_date,
                                              created_at__lte=end_date)
                order_ids = []
                for order in orders:
                    order_ids.append(order.order_id)
                orders_relation2card = orders_relation2card.filter(
                    order_id__in=order_ids)
                owner_ids = list(order.owner_id
                                 for order in orders_relation2card)
                if not filter_data_args.has_key('id__in'):
                    filter_data_args['id__in'] = owner_ids
                else:
                    old_owner_ids = filter_data_args['id__in']
                    new_owner_ids = list(
                        set(old_owner_ids).intersection(set(owner_ids)))
                    filter_data_args['id__in'] = new_owner_ids
        if filter_data_dict.has_key('money'):
            value = filter_data_dict['money']
            val1, val2 = value.split('-')
            low_money = float(val1)
            high_money = float(val2)
            owner_ids = []
            user2orders = {}
            user2money = {}
            for order in orders_relation2card.filter(event_type="使用"):
                user_id = order.owner_id
                if not user2orders.has_key(user_id):
                    user2orders[user_id] = [order]
                    user2money[user_id] = order.money
                else:
                    user2orders[user_id].append(order)
                    user2money[user_id] += order.money
            for k, v in user2money.items():
                if v >= low_money and v <= high_money:
                    owner_ids.append(k)
            filter_data_args['id__in'] = owner_ids
            orders_relation2card = orders_relation2card.filter(
                owner_id__in=owner_ids)
        if filter_data_dict.has_key('channel'):

            filter_data_args['username__contains'] = filter_data_dict[
                'channel']

        users = User.objects.filter(**filter_data_args)
        if not users.exists():
            pageinfo, result = paginator.paginate([], cur_page, count_per_page,
                                                  query_string)
            return result, [], pageinfo

    total_days, low_date, cur_date, height_date = dateutil.get_date_range(
        dateutil.get_today(), "6", 0)
    if not filter_value:
        start_date = str(low_date) + ' 00:00:00'
        end_date = str(height_date) + ' 23:59:59'
        orders = Order.objects.filter(created_at__gte=start_date,
                                      created_at__lte=end_date)
        order_ids = []
        for order in orders:
            order_ids.append(order.order_id)
        orders_relation2card = orders_relation2card.filter(
            order_id__in=order_ids)
        users = User.objects.filter(id__in=list(
            order.owner_id for order in orders_relation2card))

    # user2orders = {}
    user2card = {}
    users_id2username = {user.id: user.username for user in users}
    for order_relation2card in orders_relation2card:
        order = order_relation2card
        user_id = order.owner_id
        try:
            username = users_id2username[user_id]
        except:
            continue
        if not user2card.has_key(user_id):
            # user2orders[user_id] =[order_relation2card]
            if order.event_type == "使用":
                user2card[user_id] = {
                    'first_name': username,
                    'card_ids': set([order.card_id]),
                    'order_ids': set([order.order_id]),
                    'use_money': order.money,
                    'refund': 0
                }
            else:
                user2card[user_id] = {
                    'first_name': username,
                    'card_ids': set([order.card_id]),
                    'order_ids': set([order.order_id]),
                    'use_money': 0,
                    'refund': order.money
                }
        else:
            # user2orders[user_id].append(order_relation2card)
            if order.event_type == "使用":
                user2card_dict = user2card[user_id]
                user2card_dict['card_ids'].add(order.card_id)
                user2card_dict['order_ids'].add(order.order_id)
                user2card_dict['use_money'] += order.money
            else:
                user2card_dict = user2card[user_id]
                user2card_dict['card_ids'].add(order.card_id)
                user2card_dict['order_ids'].add(order.order_id)
                user2card_dict['refund'] += order.money
    user2card = sorted(
        user2card.items(),
        lambda x, y: cmp(float(x[1]['use_money']), float(y[1]['use_money'])),
        reverse=True)

    owner2channel = OrderedDict()
    # owner2channel['sort_attr'] = sort_attr
    for order in user2card:
        # for user_id,orders in user2card.items():
        user_id = order[0]
        orders = order[1]
        owner2channel[user_id] = {
            'first_name': orders['first_name'],
            'order_ids': list(orders['order_ids']),
            'card_ids': list(orders['card_ids']),
            'use_money': '%.2f' % float(orders['use_money']),
            'refund': '%.2f' % float(-orders['refund']),
            'order_count': len(orders['order_ids']),
            'use_count': len(orders['card_ids']),
            'sort_attr': sort_attr
        }
    user2card = sort_channel(sort_attr, owner2channel)

    if cur_page:
        pageinfo, user2card = paginator.paginate(user2card, cur_page,
                                                 count_per_page, query_string)
    channel = OrderedDict()
    for card in user2card:
        channel_card = card[1]
        channel[card[0]] = {
            'owner_id': card[0],
            'first_name': channel_card['first_name'],
            'use_money': '%.2f' % float(channel_card['use_money']),
            'refund': '%.2f' % float(channel_card['refund']),
            'order_ids': list(channel_card['order_ids']),
            'order_count': len(channel_card['order_ids']),
            'use_count': len(channel_card['card_ids']),
            'start_date': start_date,
            'end_date': end_date
        }
    channel = sort_channel(sort_attr, channel)
    # if sort_attr == "-use_money":
    #     #channel按消费金额倒序
    #     channel = sorted(channel.items(), lambda x, y: cmp(float(x[1]['use_money']), float(y[1]['use_money'])),reverse=True)
    #
    # elif sort_attr == "use_money":
    #     #channel按消费金额正序
    #     channel = sorted(channel.items(), lambda x, y: cmp(float(x[1]['use_money']), float(y[1]['use_money'])))
    #
    # elif sort_attr == "-order_count":
    #     #channel按订单数倒序
    #     channel = sorted(channel.items(), lambda x, y: cmp(x[1]['order_count'], y[1]['order_count']),reverse=True)
    # elif sort_attr == "order_count":
    #     #channel按订单数正序
    #     channel = sorted(channel.items(), lambda x, y: cmp(x[1]['order_count'], y[1]['order_count']))
    #
    # elif sort_attr == "-use_count":
    #     #channel按使用人数倒序
    #     channel = sorted(channel.items(), lambda x, y: cmp(x[1]['use_count'], y[1]['use_count']),reverse=True)
    # else:
    #     #channel按使用人数正序
    #     channel = sorted(channel.items(), lambda x, y: cmp(x[1]['use_count'], y[1]['use_count']))

    if cur_page:
        return channel, owner2channel, pageinfo
    else:
        return channel
Ejemplo n.º 15
0
def get_channel_details(filter_value,
                        owner_id=None,
                        start_date="",
                        end_date="",
                        cur_page=None,
                        count_per_page=None,
                        query_string=""):
    if not start_date and owner_id:
        total_days, start_date, cur_date, end_date = dateutil.get_date_range(
            dateutil.get_today(), "6", 0)
        start_date = str(start_date) + ' 00:00:00'
        end_date = str(end_date) + ' 23:59:59'
    webapp = WebApp.objects.all()
    if owner_id:
        webapp = webapp.filter(owner_id=owner_id)
    webapp_appids = []
    for w in webapp:
        webapp_appids.append(w.appid)
    orders = Order.by_webapp_id(webapp_appids).order_by('-created_at')
    if owner_id:
        orders = orders.filter(created_at__gte=start_date,
                               created_at__lte=end_date)
    id2order_ids = {}
    for r in orders:
        id2order_ids[r.order_id] = r.id
    order_ids = id2order_ids.keys()
    card_orders = WeizoomCardHasOrder.objects.filter(
        order_id__in=order_ids).order_by('-created_at')

    #处理过滤
    cur_event_type = '0'
    filter_data_args = {}
    filter_card_rule_ids = []
    if filter_value:
        filter_data_dict = {}
        for filter_data_item in filter_value.split('|'):
            try:
                key, value = filter_data_item.split(":")
            except:
                key = filter_data_item[:filter_data_item.find(':')]
                value = filter_data_item[filter_data_item.find(':') + 1:]

            filter_data_dict[key] = value
        created_at = filter_data_dict['created_at']
        if created_at.find('--') > -1:
            val1, val2 = created_at.split('--')
            val1 = val1 + ' 00:00:00'
            val2 = val2 + ' 23:59:59'
            if owner_id:
                if val1 < start_date:
                    val1 = start_date
                if val2 > end_date:
                    val2 = end_date
            orders = Order.by_webapp_id(webapp_appids).filter(
                created_at__gte=val1,
                created_at__lte=val2).order_by('-created_at')
            order_ids = []
            for r in orders:
                order_ids.append(r.order_id)
            card_orders = card_orders.filter(order_id__in=order_ids)
        for key, value in filter_data_dict.items():

            #卡号
            if key == 'card_id':
                card_ids = list(card.id for card in WeizoomCard.objects.filter(
                    weizoom_card_id__contains=value))
                if card_ids:
                    card_orders = card_orders.filter(card_id__in=card_ids)
            #卡名称
            if key == 'name':
                rules = WeizoomCardRule.objects.filter(name__contains=value)
                if rules:
                    for rule in rules:
                        filter_card_rule_ids.append(rule.id)
                    card_ids = list(
                        weizoom_card.id
                        for weizoom_card in WeizoomCard.objects.filter(
                            weizoom_card_rule_id__in=filter_card_rule_ids))
                    if not filter_data_args.has_key('card_id__in'):
                        # filter_data_args['card_id__in'] = card_ids
                        card_orders = card_orders.filter(card_id__in=card_ids)
                    else:
                        old_card_ids = filter_data_args['card_id__in']
                        new_card_ids = list(
                            set(old_card_ids).intersection(set(card_ids)))
                        # filter_data_args['card_id__in'] = new_card_ids
                        card_orders = card_orders.filter(
                            card_id__in=new_card_ids)
                else:
                    filter_data_args["card_id__in"] = -1
            #订单号
            if key == 'order_id':
                filter_data_args["order_id__contains"] = value

            if key == 'member':
                member_ids = []
                for member in Member.objects.filter(
                        username_hexstr__contains=byte_to_hex(value)):
                    member_ids.append(member.id)
                member_webappuser_ids = [
                    member.id for member in WebAppUser.objects.filter(
                        member_id__in=member_ids)
                ]
                if member_ids:
                    order_ids = list(order.order_id for order in orders.filter(
                        webapp_user_id__in=member_webappuser_ids))
                    filter_data_args["order_id__in"] = order_ids
                else:
                    filter_data_args["order_id"] = -1

            if key == 'status':
                if value == "4":
                    card_ids = list(card.id
                                    for card in WeizoomCard.objects.filter(
                                        is_expired=True))
                    filter_data_args['card_id__in'] = card_ids
                else:
                    card_ids = list(card.id
                                    for card in WeizoomCard.objects.filter(
                                        status=value, is_expired=False))
                    filter_data_args['card_id__in'] = card_ids
                if not filter_data_args.has_key('card_id__in'):
                    filter_data_args['card_id__in'] = card_ids
                else:
                    old_card_ids = filter_data_args['card_id__in']
                    new_card_ids = list(
                        set(old_card_ids).intersection(set(card_ids)))
                    filter_data_args['card_id__in'] = new_card_ids

            if key == 'money':
                val1, val2 = value.split('--')
                low_money = float(val1)
                high_money = float(val2)
                card2money = {}
                orderids = []
                cur_orders = WeizoomCardHasOrder.objects.filter(
                    order_id__in=order_ids)
                if cur_orders:
                    for order in cur_orders:
                        if not card2money.has_key(order.order_id):
                            if order.event_type == "使用":
                                card2money[order.order_id] = {
                                    'use_money': order.money,
                                    'refund': 0,
                                }
                            else:
                                card2money[order.order_id] = {
                                    'refund': order.money,
                                    'use_money': 0
                                }
                        else:
                            if order.event_type == "使用":
                                card2money[
                                    order.order_id]['use_money'] += order.money
                            else:
                                card2money[
                                    order.order_id]['refund'] += order.money
                if card2money:
                    for key, value in card2money.items():
                        for k, v in value.items():
                            if v >= low_money and v <= high_money and v != 0:
                                orderids.append(key)
                    if orderids:
                        if not filter_data_args.has_key('order_id__in'):
                            card_orders = card_orders.filter(
                                order_id__in=orderids)
                        else:
                            old_card_ids = filter_data_args['order_id__in']
                            new_card_ids = list(
                                set(old_card_ids).intersection(set(orderids)))
                            filter_data_args['order_id__in'] = new_card_ids
                    else:
                        filter_data_args['order_id'] = -1
            if key == 'event_type':
                cur_event_type = value
                if value == '1':
                    orders = orders.filter(status=ORDER_STATUS_CANCEL)
                    order_ids = []
                    for r in orders:
                        order_ids.append(r.order_id)
                    card_orders = card_orders.filter(order_id__in=order_ids,
                                                     event_type="返还")

                if value == '0':
                    # order_ids = []
                    # for r in orders:
                    #     order_ids.append(r.order_id)
                    card_orders = card_orders.filter(order_id__in=order_ids,
                                                     event_type="使用")
        card_orders = card_orders.filter(**filter_data_args).exclude(
            order_id=-1).order_by('-created_at')
    else:
        card_orders = card_orders.filter(event_type="使用")
    # order2card_id = OrderedDict()
    order2card_id = []
    inner_dict = OrderedDict()
    user_id2username = {u.id: u.username for u in User.objects.all()}
    for card_order in card_orders.order_by('-created_at'):
        inner_order_id = card_order.order_id
        if not inner_dict.has_key(card_order.order_id):
            if card_order.event_type == "使用":
                inner_dict[card_order.order_id] = [{
                    'order_id':
                    card_order.order_id,
                    'id':
                    id2order_ids[card_order.order_id],
                    'card_id':
                    card_order.card_id,
                    'use_money':
                    '%.2f' % card_order.money,
                    'created_at':
                    card_order.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                    'onwer_id':
                    card_order.owner_id,
                    'owner_username':
                    user_id2username[card_order.owner_id],
                    'event_type':
                    card_order.event_type
                }]
            else:
                inner_dict[card_order.order_id] = [{
                    'order_id':
                    card_order.order_id,
                    'id':
                    id2order_ids[card_order.order_id],
                    'card_id':
                    card_order.card_id,
                    'refund':
                    '%.2f' % -card_order.money,
                    'created_at':
                    card_order.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                    'onwer_id':
                    card_order.owner_id,
                    'owner_username':
                    user_id2username[card_order.owner_id],
                    'event_type':
                    card_order.event_type
                }]
        else:
            if card_order.event_type == "使用":
                inner_dict[card_order.order_id].append({
                    'card_id':
                    card_order.card_id,
                    'use_money':
                    '%.2f' % card_order.money,
                })
            else:
                inner_dict[card_order.order_id].append({
                    'card_id':
                    card_order.card_id,
                    'refund':
                    '%.2f' % -card_order.money,
                })
    temp_list = []
    for k, v in inner_dict.items():
        temp_list.append({k: v})
    order2card_id.append(inner_dict)

    # order2card_id = sorted(order2card_id.items(), lambda x, y: cmp(x[1][0]['created_at'], y[1][0]['created_at']),reverse=True)order2card_id = sorted(order2card_id.items(), lambda x, y: cmp(x[1][0]['created_at'], y[1][0]['created_at']),reverse=True)
    if cur_page:
        pageinfo, temp_list = paginator.paginate(temp_list, cur_page,
                                                 count_per_page, query_string)
        key_list = []
        for one_dict in temp_list:
            key_list.append(one_dict.keys()[0])

        needed_keys = list(set(inner_dict.keys()) ^ (set(key_list)))
        for k in needed_keys:
            del inner_dict[k]

    order_ids = set()
    card_ids = set()
    for inner_dict in order2card_id:
        # cards = card[1]
        for order_id, v in inner_dict.items():
            for card in v:
                card_ids.add(card['card_id'])
            order_ids.add(order_id)
    order_id2webapp_user_id = {}
    webapp_user_ids = []
    for order in Order.objects.filter(order_id__in=order_ids):
        order_id2webapp_user_id[order.order_id] = order.webapp_user_id
        webapp_user_ids.append(order.webapp_user_id)

    owner_ids = [
        user.id
        for user in User.objects.filter(username__in=['weshop', 'wzjx001'])
    ]
    webapp_ids = [
        webapp.appid
        for webapp in WebApp.objects.filter(owner_id__in=owner_ids)
    ]
    ids = []
    order_id2orderid = {}
    for order in Order.by_webapp_id(webapp_ids).filter(order_id__in=order_ids):
        ids.append(order.id)
        order_id2orderid[order.id] = order.order_id
    order_order_id2Product_ids = {}
    product_ids = set()
    for p in OrderHasProduct.objects.filter(order_id__in=ids):
        if not order_order_id2Product_ids.has_key(p.product_id):
            order_order_id2Product_ids[order_id2orderid[p.order_id]] = [
                p.product_id
            ]
        else:
            order_order_id2Product_ids[order_id2orderid[p.order_id]].append(
                p.product_id)
        product_ids.add(p.product_id)
    product_id2category_name = {}
    catetory_id2name = {c.id: c.name for c in ProductCategory.objects.all()}
    for p in CategoryHasProduct.objects.filter(product_id__in=product_ids):
        if not product_id2category_name.has_key(p.product_id):
            product_id2category_name[p.product_id] = [
                catetory_id2name[p.category_id]
            ]
        else:
            product_id2category_name[p.product_id].append(
                catetory_id2name[p.category_id])

    weizoom_cards = {}
    for card in WeizoomCard.objects.filter(id__in=list(card_ids)):
        status_str = u''
        if card.is_expired:
            status_str = u'己过期'
        else:
            if card.status == WEIZOOM_CARD_STATUS_UNUSED:
                status_str = u'未使用'
            if card.status == WEIZOOM_CARD_STATUS_USED:
                status_str = u'使用中'
            if card.status == WEIZOOM_CARD_STATUS_INACTIVE:
                status_str = u'未激活'
            if card.status == WEIZOOM_CARD_STATUS_EMPTY:
                status_str = u'己用完'
        weizoom_cards[card.id] = {
            'weizoom_card_id': card.weizoom_card_id,
            'weizoom_card_rule_id': card.weizoom_card_rule_id,
            'status': status_str,
        }
    rule_ids = list(
        set(card['weizoom_card_rule_id'] for card in weizoom_cards.values()))

    rules = {}
    for rule in WeizoomCardRule.objects.filter(id__in=rule_ids):
        rules[rule.id] = {
            'rule_name': rule.name,
            'rule_money': '%.2f' % rule.money
        }
    for card_id in weizoom_cards.keys():
        for rule_id in rules.keys():
            if weizoom_cards[card_id]['weizoom_card_rule_id'] == rule_id:
                weizoom_cards[card_id].update(rules[rule_id])
    all_webappuser2member = Member.members_from_webapp_user_ids(
        webapp_user_ids)
    for inner_dict in order2card_id:
        for k, orders in inner_dict.items():

            # card_orders = order[1]
            # order_id = order[0]
            order_id = k
            product_dict = orders[0]['product'] = {}
            if order_order_id2Product_ids.has_key(order_id):
                product_ids = order_order_id2Product_ids[order_id]
                for one_id in product_ids:
                    try:
                        product_dict[one_id] = ','.join(
                            product_id2category_name[one_id])
                    except:
                        product_dict[one_id] = ''

            webapp_user_id = order_id2webapp_user_id[order_id]
            member = all_webappuser2member[webapp_user_id]
            if member:
                buyer_name = member.username_for_html
            else:
                buyer_name = u'未知'
            orders[0].update({'buyer_name': buyer_name})
            for card_order in orders:
                card_id = card_order['card_id']
                card_order.update(weizoom_cards[card_id])
    if cur_page:
        return order2card_id, pageinfo, cur_event_type
    else:
        return order2card_id
Ejemplo n.º 16
0
def get_buy_trend(request):
    days = request.GET['days']
    webapp_id = request.user_profile.webapp_id
    total_days, low_date, cur_date, high_date = dateutil.get_date_range(
        dateutil.get_today(), days, 0)
    date_list = dateutil.get_date_range_list(low_date, high_date)

    date2count = dict()
    date2price = dict()

    # 11.20从查询mall_purchase_daily_statistics变更为直接统计订单表,解决mall_purchase_daily_statistics遗漏统计订单与统计时间不一样导致的统计结果不同的问题。
    orders = Order.objects.belong_to(webapp_id).filter(
        created_at__range=(low_date, (high_date + timedelta(days=1))),
        status__gte=2)

    for order in orders:
        date = dateutil.normalize_date(order.created_at)
        date = order.created_at.strftime("%Y-%m-%d")
        if order.webapp_id != webapp_id:
            order_price = Order.get_order_has_price_number(
                order) + order.postage
        else:
            order_price = order.final_price

        if date in date2count:
            old_count = date2count[date]
            date2count[date] = old_count + 1
        else:
            date2count[date] = 1

        if date in date2price:
            old_price = date2price[date]
            date2price[date] = old_price + order_price
        else:
            date2price[date] = order_price

    count_trend_values = []
    price_trend_values = []
    for loop_date in date_list:
        date = loop_date.strftime('%Y-%m-%d')
        x = (loop_date - low_date).days
        count_trend_values.append({'x': x, 'y': date2count.get(date, 0)})
        price_trend_values.append({'x': x, 'y': date2price.get(date, 0)})

    if len(count_trend_values) == 0:
        values = []
    else:
        values = [{
            'title': u'订单数',
            'values': count_trend_values
        }, {
            'title': u'销售额',
            'values': price_trend_values
        }]

    infos = {
        'title': '',
        'values': values,
        'date_info': {
            'days': total_days,
            'low_date': low_date
        }
    }

    line_chart_json = chartutil.create_line_chart(infos,
                                                  display_today_data=True)

    return HttpResponse(line_chart_json, 'application/json')