Beispiel #1
0
    def page_list(self, request, *args, **kwargs):
        request_data = request.GET
        # start_time before now
        now_dt = datetime.datetime.now()
        queryset = NinePicAdver.objects
        model_id = request_data.get('model_id')

        if request_data.get('model_id'):
            queryset = queryset.filter_by_modelproduct(request_data.get('model_id'))

        if request_data.get('ordering') is None:
            queryset = queryset.order_by('-start_time', '-turns_num')

        queryset = queryset.filter(start_time__lte=now_dt)
        queryset = self.filter_queryset(queryset)
        pagin_query = self.paginate_queryset(queryset)

        profit = {'max': 0, 'min': 0}
        if model_id:
            mp = ModelProduct.objects.filter(id=model_id).first()
            if mp:
                profit = mp.get_model_product_profit()

        for item in pagin_query:
            item.profit = profit

        serializer = self.get_serializer(pagin_query, many=True)
        response = self.get_paginated_response(serializer.data)
        # 统计代码
        xlmm = self.get_xlmm()
        if xlmm:
            statsd.incr('xiaolumm.ninepic_count')
            task_mama_daily_tab_visit_stats.delay(xlmm.id, MamaTabVisitStats.TAB_DAILY_NINEPIC)
        return response
Beispiel #2
0
    def get(self, request, *args, **kwargs):
        content = request.GET
        link_id = content.get("link_id", "") #re.compile('').match(

        id_array = re.findall("\d+", link_id)
        url = content.get('url') or ''

        if link_id and id_array and len(id_array) > 0:
            redirect_link, tab_id = self.links[int(id_array[0])]
        elif url:
            redirect_link = url
            tab_id = MamaTabVisitStats.TAB_WX_PUSH_AD
        else:
            return redirect(settings.M_SITE_URL)

        mama = None
        try:
            customer = Customer.objects.normal_customer.filter(user=request.user).first()
            mama = customer.get_xiaolumm()
        except Exception:
            pass

        if mama:
            task_mama_daily_tab_visit_stats.delay(mama.id, tab_id)

        if link_id == '4' and mama and mama.charge_status == 'uncharge':
            mama.chargemama()

        return redirect(redirect_link)
Beispiel #3
0
    def get(self, request, *args, **kwargs):
        customer = Customer.objects.normal_customer.filter(user=request.user).first()
        mama = customer.get_xiaolumm()

        if mama:
            task_mama_daily_tab_visit_stats.delay(mama.id, MamaTabVisitStats.TAB_WX_CASHOUT_APP_DOWNLOAD)

        from shopapp.weixin.service import DOWNLOAD_APP_LINK
        download_url = DOWNLOAD_APP_LINK
        return redirect(download_url)
Beispiel #4
0
    def get(self, request, *args, **kwargs):
        customer = Customer.objects.normal_customer.filter(user=request.user).first()
        if customer:
            mama = customer.get_xiaolumm()

        redirect_link = "/mall/"
        if mama:
            redirect_link = "/m/%s" % mama.id
            task_mama_daily_tab_visit_stats.delay(mama.id, MamaTabVisitStats.TAB_WX_MAMA_ACTIVATE)

        return redirect(redirect_link)
Beispiel #5
0
    def get_owner_queryset(self, request, exclude_statuses=None):
        mama_id = get_mama_id(request.user)
        qset = self.queryset.filter(mama_id=mama_id)
        task_mama_daily_tab_visit_stats.delay(mama_id, MamaTabVisitStats.TAB_CARRY_RECORD)

        # we dont return canceled record
        if exclude_statuses:
            for ex in exclude_statuses:
                qset = qset.exclude(status=ex)

        return qset.order_by('-date_field', '-created')
Beispiel #6
0
    def get_owner_queryset(self, request, carry_type, exclude_statuses=None):
        mama_id = get_mama_id(request.user)
        if carry_type == "direct":

            visit_tab = MamaTabVisitStats.TAB_ORDER_CARRY
            task_mama_daily_tab_visit_stats.delay(mama_id, visit_tab)

            return self.queryset.filter(mama_id=mama_id).order_by('-date_field', '-created')

        qset = self.queryset.filter(mama_id=mama_id)
        if exclude_statuses:
            for ex in exclude_statuses:
                qset = qset.exclude(status=ex)
        return qset.order_by('-date_field', '-created')
Beispiel #7
0
    def get_owner_queryset(self, request):
        content = request.GET
        days_from = int(content.get("from", 0))
        days_recent = int(content.get("recent", 0))

        date_field = datetime.datetime.now().date()
        if days_from > 0:
            date_field = date_field - datetime.timedelta(days=days_from)

        mama_id = get_mama_id(request.user)
        task_mama_daily_tab_visit_stats.delay(mama_id,MamaTabVisitStats.TAB_VISITOR_LIST)

        if days_recent > 0:
            date_field = date_field - datetime.timedelta(days=days_recent)
            return self.queryset.filter(mama_id=mama_id, date_field__gt=date_field).order_by('-created')
        else:
            return self.queryset.filter(mama_id=mama_id, date_field=date_field).order_by('-created')
Beispiel #8
0
    def list(self, request, *args, **kwargs):
        xlmm = self.get_xlmm()
        object_id = request.GET.get('id')
        if object_id:
            queryset = self.get_queryset().filter(id=object_id)
        else:
            queryset = self.get_today_queryset(self.get_queryset())

        if request.GET.get('ordering') is None:
            queryset = queryset.order_by('-start_time', '-turns_num')
        queryset = self.filter_queryset(queryset)
        serializer = self.get_serializer(queryset, many=True)
        # 统计代码
        if not object_id and xlmm:
            statsd.incr('xiaolumm.ninepic_count')
            task_mama_daily_tab_visit_stats.delay(xlmm.id, MamaTabVisitStats.TAB_DAILY_NINEPIC)

        return Response(serializer.data)
Beispiel #9
0
    def read_list(self, request):
        try:
            mama = request.user.customer.get_xiaolumm()
        except:
            raise exceptions.ValidationError(u'您并非登录小鹿妈妈或小鹿妈妈账号存在异常')
        if not mama:
            raise exceptions.ValidationError(u'您并非登录小鹿妈妈或小鹿妈妈账号存在异常')

        task_mama_daily_tab_visit_stats.delay(
            mama.id, MamaTabVisitStats.TAB_NOTIFICATION)

        XlmmMessage.set_all_read(mama)
        queryset, unread_cnt = XlmmMessage.get_msg_list(mama.id)
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        res = self.get_paginated_response(serializer.data)
        res.data['unread_cnt'] = unread_cnt
        return res
Beispiel #10
0
    def mama_join(self, request):
        if not request.user.is_anonymous:
            xiaoumama = request.user.customer.getXiaolumm(
            ) if request.user.customer else None
        else:
            # 1. check whether event_id is valid
            self.set_appid_and_secret(settings.WX_PUB_APPID,
                                      settings.WX_PUB_APPSECRET)
            # 2. get openid from cookie
            openid, unionid = self.get_cookie_openid_and_unoinid(request)
            if not self.valid_openid(unionid):
                # 3. get openid from gf'debug' or from using 'code' (if code exists)
                userinfo = self.get_auth_userinfo(request)
                unionid = userinfo.get("unionid")
                openid = userinfo.get("openid")
                if not self.valid_openid(unionid):
                    # 4. if we still dont have openid, we have to do oauth
                    redirect_url = self.get_snsuserinfo_redirct_url(request)
                    return redirect(redirect_url)
            xiaoumama = XiaoluMama.objects.filter(openid=unionid).first()

        if not xiaoumama:
            raise exceptions.ValidationError(u'您不是小鹿妈妈或者你的微信号未和小鹿妈妈账号绑定')

        task_mama_daily_tab_visit_stats.delay(
            xiaoumama.id, MamaTabVisitStats.TAB_MAMA_BOUTIQUE_FAQ)

        mama_id = xiaoumama.id
        administrastor_id = request.POST.get(
            'administrastor_id') or request.GET.get('administrastor_id')
        if GroupMamaAdministrator.objects.filter(mama_id=mama_id).exists():
            admin = GroupMamaAdministrator.objects.filter(
                mama_id=mama_id).first().admin
        elif administrastor_id:
            admin = XiaoluAdministrator.objects.filter(
                id=administrastor_id).first()
            if not admin:
                raise exceptions.NotFound(u'指定的管理员不存在')
        else:
            admin = XiaoluAdministrator.get_group_mincnt_admin()
        group = GroupMamaAdministrator.get_or_create(admin=admin,
                                                     mama_id=mama_id)
        return Response(self.get_serializer(admin).data)
Beispiel #11
0
    def get(self, request, *args, **kwargs):
        content = request.GET
        activity_id = content.get("activity_id", "")
        import re
        id_array = re.findall("\d+", activity_id)
        redirect_link = settings.M_SITE_URL

        if activity_id and id_array and len(id_array) > 0:
            ae = ActivityEntry.objects.filter(id=int(id_array[0])).first()
            if ae:
                redirect_link = ae.act_link
        mama = None
        try:
            customer = Customer.objects.normal_customer.filter(user=request.user).first()
            mama = customer.get_xiaolumm()
        except Exception:
            pass

        if mama:
            task_mama_daily_tab_visit_stats.delay(mama.id, MamaTabVisitStats.TAB_WX_PUSH_REDIRECT_LINK)

        return redirect(redirect_link)
Beispiel #12
0
    def customer_shop(self, request):
        decs = ['今天又上新品啦!', '天天都有新品哦!', '上新品啦赶快抢!']
        queryset = self.filter_queryset(self.get_owner_shop(request))
        mm_linkid = 0
        shop_info = None
        if queryset.exists():
            shop = queryset[0]
            customer = shop.get_customer()
            if customer:
                xlmm = customer.get_charged_mama()
                if xlmm and xlmm.last_renew_type >= XiaoluMama.ELITE:
                    mm_linkid = xlmm.id
                    from flashsale.xiaolumm.tasks import task_mama_daily_tab_visit_stats
                    task_mama_daily_tab_visit_stats.delay(
                        xlmm.id, MamaTabVisitStats.TAB_MAMA_SHOP)

            shop_info = model_to_dict(shop)

            link = '/mall/?mm_linkid={0}'.format(mm_linkid)
            preview_link = 'mall/?mm_linkid={0}'.format(mm_linkid)

            link = urllib.quote(link)
            next_link = 'm/{0}?next='.format(mm_linkid) + link
            link = urlparse.urljoin(settings.M_SITE_URL, next_link)

            preview_link = urlparse.urljoin('http://m.xiaolumeimei.com',
                                            preview_link)
            first_pro_pic = customer.thumbnail
            shop_info['shop_link'] = replace_domain(link)
            shop_info[
                'thumbnail'] = first_pro_pic  # customer.thumbnail  # 提供用户头像
            shop_info['desc'] = '{0}の精品店铺'.format(
                customer.nick) + random.choice(decs)
            shop_info['preview_shop_link'] = preview_link  # 预览链接http
            shop_info['name'] = '{0}の精品店铺'.format(customer.nick)
            shop_info['first_pro_pic'] = first_pro_pic

        return Response({"shop_info": shop_info})
Beispiel #13
0
    def get_owner_queryset(self, request):
        customer_id = get_customer_id(request.user)
        mama_id = get_mama_id(request.user)
        task_mama_daily_tab_visit_stats.delay(mama_id,MamaTabVisitStats.TAB_FANS_LIST)

        return self.queryset.filter(xlmm_cusid=customer_id).order_by('-created')
Beispiel #14
0
    def my_choice_pro(self, request):
        """
        我的选品(不添加秒杀和卖光的产品) 这里要计算用户的佣金
        """
        content = request.GET
        category = int(content.get('category', 0))  # 1童装2女装
        sort_field = content.get('sort_field', 'id')  # 排序字段
        if not request.user.is_authenticated():
            raise exceptions.APIException(u'请登录后访问')
        customer = get_object_or_404(Customer, user=request.user)
        queryset = self.get_queryset().filter(shelf_status=Product.UP_SHELF,
                                              status=Product.NORMAL,
                                              outer_id__endswith='1')
        if category == 1:
            queryset = queryset.filter(
                outer_id__startswith=itemcons.MALL_CHILD_STARTCODE)
        elif category == 2:
            queryset = queryset.filter(
                outer_id__startswith=itemcons.MALL_FEMALE_STARTCODE)
        else:
            queryset = queryset

        extra_str = 'remain_num - lock_num > 0'
        queryset = queryset.extra(where={extra_str})  # 没有卖光的 不是秒杀产品的

        product_ids = CuShopPros.objects.filter(
            customer=customer.id,
            pro_status=CuShopPros.UP_SHELF).values_list("product", flat=True)
        product_ids = set(product_ids)
        shop_product_num = len(product_ids)
        xlmm = customer.get_charged_mama()

        visit_tab = MamaTabVisitStats.TAB_CARRY_LIST
        from flashsale.xiaolumm.tasks import task_mama_daily_tab_visit_stats
        task_mama_daily_tab_visit_stats.delay(xlmm.id, visit_tab)

        from flashsale.xiaolumm.models.models_rebeta import AgencyOrderRebetaScheme
        next_agentinfo = xlmm.next_agencylevel_info()
        for pro in queryset:
            pro.in_customer_shop = 1 if pro.id in product_ids else 0
            rebeta_scheme_id = pro.detail and pro.detail.rebeta_scheme_id or 0
            rebate_scheme = AgencyOrderRebetaScheme.get_rebeta_scheme(
                rebeta_scheme_id)
            rebet_amount = rebate_scheme.calculate_carry(
                xlmm.agencylevel, pro.agent_price)
            pro.rebet_amount = round(rebet_amount, 2)
            pro.rebet_amount_des = u'佣 ¥{0}'.format(pro.rebet_amount)

            next_rebet_amount = rebate_scheme and rebate_scheme.calculate_carry(
                next_agentinfo[0], pro.agent_price) or 0
            pro.next_rebet_amount = round(next_rebet_amount, 2)
            pro.next_rebet_amount_des = u'佣 ¥{0}'.format(pro.next_rebet_amount)

        if sort_field in [
                'id', 'sale_num', 'rebet_amount', 'std_sale_price',
                'agent_price'
        ]:
            queryset = sorted(queryset,
                              key=lambda k: getattr(k, sort_field),
                              reverse=True)

        queryset = self.paginate_queryset(queryset)
        serializer = serializersv2.ProductSimpleSerializerV2(
            queryset,
            many=True,
            context={
                'request': request,
                'xlmm': xlmm,
                "shop_product_num": shop_product_num
            })
        return self.get_paginated_response(serializer.data)
Beispiel #15
0
def handleWeiXinMenuRequest(openid, wxpubId, event, eventKey):
    """ 2016-4-3 微信公众号常见问题请求处理 """
    from_username = openid
    to_username = wxpubId
    ret_params = {
        'ToUserName': from_username,
        'FromUserName': to_username,
        'CreateTime': int(time.time())
    }
    try:
        wx_api = WeiXinAPI(wxpubId=wxpubId)
        unionid = WeixinUnionID.get_unionid_by_openid(openid,
                                                      wx_api.getAppKey())
        mama = XiaoluMama.objects.filter(openid=unionid).first()
        if mama:
            # Statistics for weixin tab
            mama_id = mama.id
            if eventKey == 'faqs':
                task_mama_daily_tab_visit_stats.delay(
                    mama_id, MamaTabVisitStats.TAB_WX_KEFU)
            elif eventKey == 'MAMA_REFERAL_QRCODE':
                task_mama_daily_tab_visit_stats.delay(
                    mama_id, MamaTabVisitStats.TAB_WX_REFERAL_QRCODE)
            elif eventKey == 'MAMA_MANAGER_QRCODE':
                task_mama_daily_tab_visit_stats.delay(
                    mama_id, MamaTabVisitStats.TAB_WX_MANAGER_QRCODE)
            elif eventKey.strip() == DOWNLOAD_APP_LINK:
                task_mama_daily_tab_visit_stats.delay(
                    mama_id, MamaTabVisitStats.TAB_WX_APP_DOWNLOAD)
            elif eventKey.strip() == PERSONAL_PAGE_LINK:
                task_mama_daily_tab_visit_stats.delay(
                    mama_id, MamaTabVisitStats.TAB_WX_PERSONAL)

        eventKey = eventKey.upper()
        if eventKey == 'FAQS':
            faq = WeiXinAutoResponse.objects.filter(
                rtype=WeiXinAutoResponse.WX_NEWS, message=eventKey).get()
            if faq:
                ret_params.update(faq.respNews())
                return ret_params

        if event == WeiXinAutoResponse.WX_EVENT_SCAN.lower() or \
            event == WeiXinAutoResponse.WX_EVENT_SUBSCRIBE.lower():
            # tips = u'(友情提示: 小鹿美美从未也不会发起任何形式的积赞活动,传播积赞活动者均为诈骗,请大家不要参与!)'
            ret_params.update({
                'MsgType': WeiXinAutoResponse.WX_TEXT,
                'Content': u"么么哒!终于等到你!点击底部菜单选择您需要的服务吧!"
                #u'[玫瑰]亲,这是您的专属二维码,快告诉好友来开店赚佣金吧!'
            })

        if eventKey == 'MAMA_REFERAL_QRCODE':
            if mama:
                cache_key = 'wxpub_mama_referal_qrcode_mama_id_%s_%s' % (
                    wxpubId, mama.id)
                cache_value = cache.get(cache_key)
                if cache_value:
                    ret_params.update({
                        'MsgType': WeiXinAutoResponse.WX_IMAGE,
                        'Image': {
                            'MediaId': cache_value
                        }
                    })
                    return ret_params

            tasks.task_create_mama_referal_qrcode_and_response_weixin.delay(
                to_username, from_username, event, eventKey)
            ret_params.update({
                'MsgType':
                WeiXinAutoResponse.WX_TEXT,
                'Content':
                u"想你了! \n您的专属二维码正在创建中\n请5秒后重新点击菜单\n[我的收入]->[开店二维码]获取.\n健康美丽尽在小鹿美美!"
                #u'[玫瑰]亲,这是您的专属二维码,快告诉好友来开店赚佣金吧!'
            })

        if eventKey == 'MAMA_MANAGER_QRCODE':
            if mama:
                cache_value = fetch_wxpub_mama_manager_qrcode_media_id(
                    mama.id, wxpubId)
                if cache_value:
                    ret_params.update({
                        'MsgType': WeiXinAutoResponse.WX_IMAGE,
                        'Image': {
                            'MediaId': cache_value
                        }
                    })
                    return ret_params
            tasks.task_create_mama_and_response_manager_qrcode.delay(
                to_username, from_username, event, eventKey)
            ret_params.update({
                'MsgType':
                WeiXinAutoResponse.WX_TEXT,
                'Content':
                u'[爱心]亲,请长按识别图中二维码, 添加您的专属管理员微信 (若5秒内未返回请重试):'
            })

        if eventKey.startswith('JIMAY_AGENT_'):
            from flashsale.pay.models import Customer
            from flashsale.jimay.models import JimayAgent
            from flashsale.jimay.tasks import task_weixin_asynchronous_send_certification, task_weixin_asynchronous_send_awardcomplete
            customer = Customer.objects.filter(
                unionid=unionid).order_by('status').first()
            agent = None
            if customer and customer.mobile:
                agent = JimayAgent.objects.filter(
                    mobile=customer.mobile).first()

            if not customer.mobile:
                ret_params.update({
                    'MsgType': WeiXinAutoResponse.WX_TEXT,
                    'Content': u'[爱心]亲,您还没有验证手机号码,请点击菜单[订货]完成操作.'
                })
                return ret_params

            if not agent:
                ret_params.update({
                    'MsgType':
                    WeiXinAutoResponse.WX_TEXT,
                    'Content':
                    u'[爱心]亲,您还不是正式的己美医学特约代理,请联系管理员申请加入.'
                })
                return ret_params

            innerKey = eventKey.split('_')[-1]
            if innerKey == 'EDUCATED' and not agent.is_graduated:
                ret_params.update({
                    'MsgType': WeiXinAutoResponse.WX_TEXT,
                    'Content': u'[爱心]亲爱的,您还没有毕业,暂无法创建毕业证书.'
                })
                return ret_params

            if innerKey == 'CERTIFICATION':
                task_weixin_asynchronous_send_certification.delay(
                    wxpubId, agent.id)

            if innerKey == 'EDUCATED':
                task_weixin_asynchronous_send_awardcomplete.delay(
                    wxpubId, agent.id)

            ret_params.update({
                'MsgType': WeiXinAutoResponse.WX_TEXT,
                'Content': u'[爱心]亲,您的证书正在生成(若5秒内未返回请重试).'
            })

        if eventKey.startswith('JIMAY_PAY_'):
            from flashsale.pay.models import Customer
            from flashsale.jimay.models import JimayAgent
            from flashsale.jimay.tasks import task_weixin_asynchronous_send_payqrcode
            customer = Customer.objects.filter(
                unionid=unionid).order_by('status').first()
            agent = None
            qrcodeKey = eventKey.split('_')[-1]
            if customer and customer.mobile:
                agent = JimayAgent.objects.filter(
                    mobile=customer.mobile).first()

            if not customer.mobile:
                ret_params.update({
                    'MsgType': WeiXinAutoResponse.WX_TEXT,
                    'Content': u'[爱心]亲,您还没有验证手机号码,请点击菜单[订货]完成操作.'
                })
                return ret_params

            if not agent:
                ret_params.update({
                    'MsgType':
                    WeiXinAutoResponse.WX_TEXT,
                    'Content':
                    u'[爱心]亲,您还不是正式的己美医学特约代理,请联系管理员申请加入.'
                })
                return ret_params

            task_weixin_asynchronous_send_payqrcode.delay(
                wxpubId, customer.id, qrcodeKey)

            ret_params.update({
                'MsgType': WeiXinAutoResponse.WX_TEXT,
                'Content': u'[爱心]亲,您的付款码正在生成(若5秒内未返回请重试).'
            })

    except Exception, exc:
        logger.error(u'handleWeiXinMenuRequest error: %s' % exc.message,
                     exc_info=True)
        ret_params.update({
            'MsgType': WeiXinAutoResponse.WX_TEXT,
            'Content': u'Sorry亲,系统负载太高,请稍等![撇嘴]'
        })